Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django AJAX POST action that redirects user to login URL if not logged in
I am using django 3.2 I am trying to implement functionality that I have seen on other websites - where when you try to comment (for example), without login, it redirects you to the login page. It is trivial to do this for GET routes - however, it is not clear to me, how to implement this functionality for AJAX POST functions. Example: /path/to/myapp/views.py class FoobarMixin(LoginRequiredMixin, UserPassesTestMixin): def test_func(self): user = self.request.user if user.is_superuser: return True return some_foobar_test() class FooCreateView(FoobarMixin, CreateView): http_method_names = ['post'] context_object_name = 'foo_object' def get_object(self, queryset): content_type = self.request.POST.get('ct') object_id = self.request.POST.get('id') self.foo_object = get_object_by_content_type_and_object_id(content_type, object_id) return self.foo_object def post(self, request, *args, **kwargs): foo_object = self.foo_object retval = foo_object.just_do_it(self.request.user) new_count = foo_object.foo_count if retval else None return JsonResponse({'retval': retval, 'new_count': foo_count}) /path/to/myapp/urls.py ... path('whatever/foo/', views_foo.FooCreateView.as_view(), name='do-foo'), ... /path/to/myapp/templates/myapp/page.html {% extend 'base.html' %} {% load static %} {% block content %} <a class="foo"><i class="foo fa fa-smile-o</i></a> {%end block %} {% block body_js %} $('a.foo, a.foo > i').on('click', function(e){ $.ajax({ type: "POST", url: "{% url 'do-foo' %}", data: { ct: '{{ content_type }}', id: '{{ foo_id }}', csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: "json", success: function(resultData){ console.log(resultData); }, error: function(xhr, status, error) { console.log(status); console.log(`error from server: ${status}`); … -
How to have a field only supereditable in Django?
Note I know this question has been asked previously but i am using that suggestion only but not giving me desired result my model class QuestionModel(models.Model): question = models.TextField() mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True, blank=True) answer = models.TextField(default="", blank=True) my admin.py class QuestionAdmin(admin.ModelAdmin): def get_readonly_fields(self, request): fields = super().get_readonly_fields(request) if not request.user.is_superuser: fields.append('answer') return fields admin.site.register(QuestionModel, QuestionAdmin) i am trying to make this answer field onlyt superuser editable thats how i ma doing but a normal user is also able to update it but a simple put request, so how to prevent that user from updating -
I want to add Three js project to Django Project. Can anyone Guide me in how to update settings.py file and show the tree structure of the directory
This is my settings.py file STATICFILES_DIRS = [ "/rios/search/static/", "/rios/user/static/", "node_modules" ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django_node_assets.finders.NodeModulesFinder', 'npm.finders.NpmFinder' ] NODE_PACKAGE_JSON = 'package.json' NODE_MODULES_ROOT = 'node_modules' I used this library django-node-assets https://pypi.org/project/django-node-assets/ The image shows how my folders and files are arranged in Project Directory My Tree Structure -
how to reduce list chart to one and use select dropdown to show selection without refresh page?
I am a beginner learning to make charts with pandas converted in json format. I have a lot of graph against the data, but it takes a lot of space; so i would like to know how can i make a filter and only display what the user want to see. I read some tutorial that made with dropdowns with html, but the problem is that I have to do this dynamically and depending on the size of the data, do you have any suggestions for the process? var trend_axe = {{trend_axe | safe}}; for (i in trend_axe){ var item = JSON.parse(trend_axe[i]); var label = []; for (j in item){ label.push(item[j].date_); } var stock = []; for (k in item){ stock.push(item[k].stock); } new Chart(document.getElementById(item[i].axe),{ type :'line', data :{ labels: label, datasets: [{ label: 'Trend journalier des ventes', data: stock, fill: false, borderColor: '#0E9036', tension: 0.1 }] }, }); }; what i could do : <div class="chart"> <canvas id="MDVS1"></canvas> <canvas id="MDV03"></canvas> <canvas id="MDV01"></canvas> <canvas id="MDV04"></canvas> </div> -
Collapse Django NavBar on Hover (Mouse out)
I am in need to hide a django app navbar on mouse out and show on mouse over just like in 1. The django app is using Bootstrap4. According to W3School BootStrap4 has .collapse class 2. From a BootStrap4 perspective, I am still figuring out I could use the collapse class with hover. On the other hand, by just using css, I went through the first attempt following something like in 3. HTML <div id="nav_general"> <nav id="navbar" class="navbar navbar-inverse navbar-fixed-top" role="navigation"> </nav> </div> CSS .home #navbar { display: flex; transform: translateY(-100%); } .home #nav_general:hover #navbar { transform: translateY(0); } Within the CSS configuration the navbar was hidden forever and it is not expanding on mouse over. Could anyone point me the reason the navbar has been hidden forever and how I could make it expand on mouse over? How I could achieve the same goal by just using BootStrap4 class=collapse? -
Django runserver is not working with ModuleNotFoundError: No module named 'test' error
Getting the below error when I am running the python app/manage.py runserver command. Not sure what is going wrong there. I tried with different version of django and getting the same error with all django version. Python: 3.6.6 Django: 3.1.5 ubuntu: 14.04 Error: root@e1dd33f6a3ef:/code# python app/manage.py runserver --noreload Traceback (most recent call last): File "app/manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'test' -
Accessing primary key in Django class based view
Accessing primary keys in Django class based view Let's start from the beginning. I have 2 models, Recipe, and Ingredient. They look like this. In models.py class Recipe(models.Model): name=models.CharField(max_length=20, help_text='Enter the name of this recipe') description=models.TextField(max_length=75, help_text='Describe your recipe') def __str__(self): return self.name def get_absolute_url(self): return reverse('recipe-detail', kwargs={'pk': self.pk`}) class Ingredient(models.Model): recipe=models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient=models.CharField(max_length=100) class Meta: ordering = ['ingredient'] def __str__(self): return self.ingredient What I want to be able to do is have a detail view, where I can access the Recipe attributes, like the name and description, as well as, be able to loop through the ingredients. This is what I have working so far: In views.py def recipe_detail_view(request, pk): recipe = get_object_or_404(Recipe, pk=pk) context = { 'recipe': recipe, 'ingredients': Ingredient.objects.filter(recipe=pk) } return render(request, 'recipes/recipe_detail.html', context=context) In urls.py # ... path('recipes/<str:pk>', views.recipe_detail_view, name='recipe-detail') # ... In template <h1 class="title is-1">{{ recipe.name }}</h1> <p>{{ recipe.description }}</p> <h3 class="title">Ingredients</h3> {% for ingredient in ingredients %} <h4 class="">{{ ingredient.ingredient.title }}</h3> {% endfor %} I am wondering how I could turn this into a class based view however. More specifically, I am wondering how I can access and pass in the primary key to the filter like so: class RecipeDetailView(generic.DetailView): model = Recipe … -
i m unable to fetch profile pic
i have a default profile pixand want to show it in my html but unable to get it html code <img class="profile-pic nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="max-width: 45px; max-height:45px; border-radius: 50%;" src="{{ user.accounts.profile.profile_pic.url }}" > model class Profile_Pic(models.Model): user = models.OneToOneField(User ,on_delete=models.CASCADE,) profile_pic = models.ImageField(upload_to='profile_pics', default='default.png',) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username -
while user hover on anchor tag link then a drop down should open
below is my code where where I have mention one is an anchor tag in anchor tag I have given a "class=trigger". In that anchor tag I have main categories and after that anchor tag I have given a div which is also defines with "class=sub". In this div I have complete sub categories. Know I am trying to achieve like while user hover on achor tag which is "class=trigger" then the div which is "class=sub" should display on hovering at anchor tag. So how can we achieve this using css or javascript. <a class="trigger" href="{% url 'getProductsByCategory' Categories.cat_name %}">{{Categories.cat_name}}</a> <div class="sub"> {% for subCategories in SubCategoriesBar %} {% if Categories.cat_id == subCategories.parent_id %} <div class="item">{{subCategories.cat_name}}</div> {% endif %} {% endfor %} </div> -
Deploying Django on Heroku
I am trying to dploy my django application on heroku and keep getting this error message: ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xo9jsddf/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-xo9jsddf/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-xuxym03s/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.9/psycopg2 Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed``` I have my Procfile and requirements.txt. Any help is appreciated! -
ModuleNotFoundError: No module named 'pip' on virtual environment
Pip doesn't work in my virtual environment. As I create a virtual env, it works fine for the first time, and it doesn't seem to work the next time. Even after I upgrade pip to the latest version, it throws the same error. How may I solve this issue? pip freeze Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "D:\Fast\name\venv\Scripts\pip.exe_main.py", line 4, in ModuleNotFoundError: No module named 'pip' -
Oauth2: How does this exactly works and How to implement it on the oauth2 client part?
There is an oauth2 client which is an application developed in django and oauth2 provider also an application in PHP CI. The Django application should authenticate users from the PHP application and let the users run the Django application with their accounts. I am confused about how the oauth2 works. Still, I am not able to figure the situation here. I tried looking from the docs: https://django-oauth-toolkit.readthedocs.io/en/latest/ I just have to work as being the oauth2 client. Can someone explain how this works? -
Android Paypal Native Checkout Sdk Endless loading
I am using server-side integration of paypal python sdk. I create the order on the server-side. Now I want a user to pay on my mobile kotlin app. For this I am using the paypal android native checkout sdk. For testing I copy the orderId from the server-side and paste it into the paypalButton.setup, now paypal let me log in with me personal sandbox account, but if I click on continue i am stuck in an endless loading loop and nothing happens. Thank you for helping. In the screenshot is how I use the paypalbutton The order Id is pasted from the server That is how the order is created on the server-side -
You have multiple authentication backends configured Django?
I am having this error You have multiple authentication backends configured and therefore must provide the `backend` argument or set the `backend` attribute on the user. in my Login class base view in Django Login View class SystemLoginView(LoginView): template_name = "registration/login.html" authentication_form = LoginForm def post(self, request, *args, **kwargs): username = request.POST['username'] password = request.POST['password'] db_name = request.POST['year'] branch = request.POST["branch"] user = authenticate(username=username, password=password) if user and user.active: period_id = AccountingPeriod.objects.all() if period_id: request.session["period_id"] = period_id[0].id else: request.session["period_id"] = None messages.error( request, _( "Please You must Be initial the Period Before Any Operation" ), ) set_defualt( request.session.session_key, int(branch), ) request.session["branch_id"] = branch cache.set("branch", branch) list_branch = [] for x in user.user_branch.all(): dict_data = {"id": x.pk, "name": x.name} list_branch.append(dict_data) request.session["user_branch"] = list_branch request.session["db_name"] = db_name request.session["permission"] = get_all(request) request.session["permission_partion"] = get_all_partion(request) request.session["db_name"] = db_name return super(SystemLoginView, self).post(request, *args, **kwargs) Login Form class class LoginForm(AuthenticationForm, IttechForm): CHOICE = [(x, x) for x in DATABASES] year = forms.ChoiceField( choices=CHOICE, label=_("Year"), widget=forms.Select(attrs={"class": "form-control"}) ) branch = forms.ModelChoiceField( queryset=Branch.objects.all(), label=_("Branch"), widget=forms.Select(attrs={"class": "form-control"}) ) username = forms.CharField( label=_("Username"), max_length=20, widget=forms.TextInput(attrs={"placeholder": _("Username"), "class": "form-control"}), ) password = forms.CharField( label=_("password"), max_length=30, widget=forms.PasswordInput(attrs={"placeholder": _("Password"), "class": "form-control"}), ) def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) def clean(self): username = … -
DRF how to add loggedin user to serializer field
I want to auto add my loggedin user. From DRF tutorial and other stackoverflow questions I write this code but facing error TypeError at /articles/write/ getattr(): attribute name must be string Request Method: POST Request URL: http://127.0.0.1:8000/articles/write/ Django Version: 3.2.4 Exception Type: TypeError Exception Value: getattr(): attribute name must be string Here are code model.py class ArticlesModel(models.Model): title = models.CharField('Enter Your title', max_length=150) body = models.TextField('What is on your mind') image = models.ImageField(upload_to='articles', blank=True, null=True) slug = AutoSlugField(populate_from=title) date_added = models.DateTimeField(auto_now_add=True) author = models.ForeignKey('auth.User', on_delete=models.CASCADE) class Meta: ordering = ('-date_added', 'image',) def __str__(self): return f'{self.title} by {self.author.username} at {self.date_added}' def get_absolute_url(self): return f'http://localhost:8000/media/{self.image}' def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url else: return '' serializers.py class ArticlesSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source='author.username') class Meta: model = ArticlesModel fields = ['id', 'title', 'body', 'image', 'get_absolute_url', 'author'] def create(self, validated_data): return ArticlesModel.objects.create(**validated_data) views.py class WriteArticleView(APIView): permission_classes = [IsAuthenticated,] def post(self, request): serializer = ArticlesSerializer(data=request.data) if serializer.is_valid(): serializer.save(author=request.user) return Response(status=status.HTTP_201_CREATED) return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
fields.E305 reverse query name clashes with reverse query name
I would like to have audit columns in each model. However, once two models have the same code, I get an error "(fields.E305) Reverse query name for 'app.Model.created_on' clashes with the reverse query name for 'app.Model.created_on'. created_on created_by updated_on updated_by Example class ModelB(models.Model): created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='created_by', on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='updated_by', on_delete=models.CASCADE) class ModelB(models.Model): created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='created_by', on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='updated_by', on_delete=models.CASCADE) I don't really need a reverse key in users for each of these, but I want a way to be able to lookup the user_id if necessary. -
How to create a model field that is an average of all of another foreign key model' field. Ex: avg rating field
I have two models. Fiction model that can be any movie, book, tv series or something similar. I have another model that is a review that contain review like fields for example: reviewer, rating, description. What I want to do is the following: Have Two extra fields in the fiction model that are: number of reviews average of review ratings I was able to add them as integer and float fields and then changed them whenever a new review was added, edited, or deleted but there are two issues. Adding reviews from the admin won't be accounted for I just feel like that is not the best approach and I feel like there is a more sensible approach for the fields to be automatically filled from the review model. Here are the two models as well as how I implemented the api views. fiction models.py from django.db import models from stream.models import StreamPlatform class Fiction(models.Model): """ Model that encopasses a Movie, TV Series, book or similar """ MOVIE = 1 TV_SERIES = 2 BOOK = 3 PODCAST = 4 TYPE = ( (MOVIE, 'Movie'), (TV_SERIES, 'TV-Series'), (BOOK, 'Book'), (PODCAST, 'Podcast') ) title = models.CharField(max_length=50) description = models.CharField(max_length=200) active = models.BooleanField(default=True) … -
how to enable submit button after successful validation in jquery
So I have two button: <div class="field-row"> <button type="submit" class="form-button" id="validate" style="cursor: pointer;">Validate</button> <button type="submit" class="form-button" id="submit" style="cursor: pointer;">Submit</button> </div> I want to disable the submit button in the start and then after the form is validated by the validate button by INSERT Query a string is passed from the server side, I need to enable the submit button and disable the validate button when the string is shown. If someone can please help me, Im fairly new to jquery. -
How can i request cart objects from post list view?
This is my post listview where i want the cart object to be. but i keep getting this error 'PostListView' object has no attribute 'cart'. Am not sure if it is a good practice to write a dispatcher to handle that functionality of rending the cart object ? from cart.cart import Cart class PostListView(ListView): model = Post template_name = 'feed/feed.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def dispatch(self, request, *args, **kwargs): cart = Cart(request) if self.cart: return cart def get_context_data(self,**kwargs): context = super(PostListView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: liked = [i for i in Post.objects.all() if Like.objects.filter(user = self.request.user, post=i)] context['liked_post'] = liked for user in Post.objects.all(): if self.request.user.is_authenticated: friend_list = FriendList.objects.get(user=self.request.user ) friends = friend_list.friends.all() context['friends'] = friends return context Here is my cart detail view, i have tried writing a context for it but i had another error saying post has no attribute request and now wondering how i can get users on the app to accesses the cart object when they are on the post listview ? def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={'quantity': item['quantity'], 'update':True}) return render(request, 'cart/detail.html',{'cart':cart}) -
Django Models create a task for all users
So i'm trying to build a webapp where the same task is given to all users, and when the users complete the task they can mark it as completed, to do so i added a 'status' bool that is set to true when the 'task' is not complete, and with a button the user can set it to false, the problem is that when i use a many-to-many field, if one user changes the 'status', it changes for everyone. I also tried using a Foreignkey but if i use a Foreignkey i have to create a task for every user. What i want is to create a task, assign it to all users, and then all the users can interact with the task without affecting what other users see. These are the models that i created (it's in spanish): class Usuario(AbstractUser): pass class Tps(models.Model): users = models.ForeignKey(Usuario, on_delete=CASCADE) titulo = models.CharField(max_length=100) TECNOLOGIA_DE_LA_FABRICACION = 'TDF' MANTENIMIENTO_Y_REPARACION_DE_EQUIPOS = 'MYRDE' MAQUINAS_ELECTRICAS_Y_ENSAYOS = 'MEYE' SEGURIDAD_E_HIGIENE_INDUSTRIAL = 'SEHI' LABORATORIO_DE_ENSAYOS_INDUSTRIALES = 'LDEI' INSTALACIONES_INDUSTRIALES = 'II' RELACIONES_HUMANAS = 'RH' TALLER_DE_ELECTROMECANICA = 'TE' ORGANIZACION_INDUSTRIAL = 'OI' INSTALACIONES_ELECTRICAS = 'IE' EDUCACION_FISICA = 'EF' EQUIPOS_Y_APARATOS_DE_MANIOBRA_Y_TRANSPORTE = 'EYADMYT' MATERIAS_CHOICES = [ (TECNOLOGIA_DE_LA_FABRICACION, 'Tecnologia de la fabricación'), (MANTENIMIENTO_Y_REPARACION_DE_EQUIPOS, 'Mantenimiento y R de … -
Django Model with foreign key relationships exceeding 1664 'SELECT' SQL entries
In my django model 'AllocatedTemplates', I have the following fields: template_job_id = models.ForeignKey(JobTemplate, related_name='jobtemplate_id', on_delete=models.CASCADE) interview_job_id = models.ForeignKey(Job, on_delete=models.CASCADE, null=True, blank=True) interview_company_id = models.ForeignKey(Company, related_name='company_id', on_delete=models.CASCADE) created_at = models.DateTimeField(default=now, blank=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, on_delete=models.CASCADE, null=True) I am using Postgres DB. When I am trying to access this model from the admin, it get the following error: 'target lists can have at most 1664 entries' What's happening is that the foreignkey relationships are calling more than 1664 'SELECT' sql queries which is exceeding the limit. What I can do to ensure that the 'SELECT' sql queries are below 1664 queries at the time with the existing model fields? -
Occurrence of a failure to migrate a Django
An error occurs when I use commands related to migration. File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/Users/jch/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/jch/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/Users/jch/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/jch/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/Users/jch/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/Users/jch/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/jch/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/Users/jch/venv/lib/python3.8/site-packages/django/db/backends/dummy/base.py", line 20, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. As an exception, if I use "python3 managy.py makemigrations", "No changes detected" is output. The first app is notice. If only notice connects to db, it will work normally. #/notice/models.py from django.db import models from django.db.models.base … -
How can I use distinct() with an F() expression?
My count contains duplicates in this query: items = items.annotate( user_id=F("product__productitemweightthroughmodel__product_item__user_id"), start_month=TruncMonth("start") ) \ .values("user_id", "start_month") \ .annotate(count=Count("start_month")) I would need to apply distinct() to the F expression somehow to avoid getting duplicates, is this possible? -
How to deploy webpack generated html file?
I run webpack to generate the js/css for my Django app, and it generates two things: (1) transpiled, packed, and versioned js/css files under myapp/static/myapp/ (the versioning uses the hased content of the file, e.g. myapp.7dd0fe49a6586234d7e7.min.js). (2) Since the version specifier is not very human friendly, and to make sure all files are included, the following file is created as myapp/templates/myapp/include-scripts.html: {% load staticfiles %} {% if debug %} <script src="{% static "myapp/js/myapp.min.js" %}"></script> <link rel="stylesheet" href="{% static "myapp/css/myapp.css" %}" type="text/css"> {% else %} <script src="{% static "myapp/js/myapp.7dd0fe49a6586234d7e7.min.js" %}"></script> <link rel="stylesheet" href="{% static "myapp/css/myapp.dd0a677adcba9309426a.css" %}" type="text/css"> {% endif %} This way production usage will get the versioned files, and consumers of myapp can include the the latest version of the generated files by simply: {% include "myapp/include-scripts.html" %} Now I want our gitlab pipeline to automate the process. Building the libraries is not problematic, since they're versioned we can push them to our static server immediately: workflow: rules: - if: $CI_COMMIT_MESSAGE =~ /^no-pipeline/ when: never - when: always webpack: stage: deploy image: thebjorn/dknode2:latest # has rsync ssh-client yarn etc. installed variables: DKBUILD_TYPE: "PRODUCTION" # our webpack looks at this to create versioned resources before_script: - eval $(ssh-agent -s) - ssh-add … -
Onclick not working in Vuejs axios response (Django)
Fisrt of all sorry for the long question. Since Vue JS performance is very good as compared to some of other platform (Based on test criteria). I render some html to a span through axiom response. But button (in the response html) click not working and also vue js data also not displaying. Here is my code <div id="vue-app" class="container"> {%csrf_token%} <button v-on:click="greet" class="btn btn-primary">BUTTON</button> <span v-html="message"></span> </div> <script type="text/javascript"> let app = new Vue({ el: "#vue-app", delimiters: ['[[', ']]'], data: { message: "", }, methods: { greet: function (event) { let formData = new FormData(); formData.append('csrfmiddlewaretoken', document.getElementsByName('csrfmiddlewaretoken')[0].value); axios({ method: 'post', url: '{% url "core:test_url" %}', data: formData }).then( response => (new Vue.set(this, 'message', response.data)) ); } } }); </script> Django view class test_func4(View): def post(self, request): return render(request, 'home/vue_js_axiom.html', { "post_to_view": 123 }) vue_js_axiom.html <table class="table table-striped"> <tr> <td>DATA FROM DJANGO VIEW</td><td>DATA FROM VUE JS</td> <td>ON CLICK BUTTON</td> </tr> <tr> <td>{{post_to_view}}</td><td>[[vue_js_variable]]</td> <td> <button v-on:click="click_from_response_view" class="btn btn-warning btn-sm">ON CLICK</button> </td> </tr> </table> <script> let container = new Vue({ el: '#container', delimiters: ['[[', ']]'], data: { vue_js_variable: "true", }, methods: { click_from_response_view: function (event) { alert("clicked from response view"); } }, }); </script> Can someone help to solve this problem? How …