Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to include authentication in a group of everyone in django?
How to include authentication in a group of everyone in django? for example. Main group router / (how to add group authentication here?) -- /route1 Route 1 -- /route2 Route 2 Is it easy to understand? Thank you. -
Django - Sorting posts by categories
I have two models -BlogPost and PostTopic. I would like to be able to filter by topic and see all the posts for that topic. This is working when I load up each url directly (i.e blog/cat/1), however when linking to this from the main blog post list view, I have tried the below template code: {% for topic in object_list %} <li><a href="{% url 'blog:BlogPostTopic_list' pk=topic.pk %}">{{ topic.topic }}</a></li> {% endfor %} However this doesn't work as it iterates over each topic mapped to the post (resulting in duplicates), rather than each unique topic. How do I link just to the unique topic page? models.py class PostTopic(models.Model): top_name = models.CharField(max_length=264, unique=True) def __str__(self): return self.top_name class BlogPost(models.Model): title = models.CharField(max_length=200) snippet = models.CharField(max_length=400, null=True) blog_pic = models.ImageField(upload_to='blog_pics', default='placeholder.jpg') hero_pic = models.ImageField(upload_to='blog_pics',blank=True) content = models.TextField() topic = models.ForeignKey(PostTopic, on_delete=models.CASCADE) create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def get_absolute_url(self): return reverse("BlogPost_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title views.py class BlogPostListView(ListView): model = BlogPost paginate_by = 4 def get_queryset(self): return BlogPost.objects.all().order_by('-published_date') class BlogPostDetailView(DetailView): model = BlogPost class BlogPostTopicListView(ListView): model = BlogPost template_name = 'blog/post_category.html' def get_queryset(self): return BlogPost.objects.filter(topic=self.kwargs['pk'] ) url url(r'^$',views.BlogPostListView.as_view(),name='BlogPost_list'), url(r'^(?P<pk>\d+)$',views.BlogPostDetailView.as_view(),name='BlogPost_detail'), url(r'^cat/(?P<pk>\d+)$',views.BlogPostTopicListView.as_view(), name='BlogPostTopic_list'), -
Who to display image in Django
I'm very new to Django so I saved an image into the database inside my models.py class Article(models.Model): title = models.CharField(max_length=120) content = models.TextField() active = models.BooleanField(default=True) picture = models.ImageField(upload_to='documents/pictures', null=True) now I want to display this image and I used the get_absolute_url method to get the current data from a row inside the db: def get_absolute_url(self): return f'/blog/{self.id}' In the views.py I return a renderfun with the params 'article':get_object_or_404(Article, id=my_id). Now in my template index.html I have this {% block content %} {{ article.content }} <img src="{{ article.picture }}" style="width: 200px; height: 200px;" /> {% endblock %} But if I open the developer console in chrome the img path is the same I set in models.py. The document/pictures folder is at the root of the django app. I tried to move it into the current app (Blog) but this also doesnt work. Do I have to set the media path in the settings.py ? I use django 3 and sqlite3 as db -
customize registration form in django
I created a registration form in django with blow codes forms.py: class UserFormRegistration(UserCreationForm): username = forms.CharField(label = 'نام کاربری') email = forms.EmailField(required=True, label = 'ایمیل') password1 = forms.CharField(label= 'رمزعبور', widget = forms.PasswordInput, strip = False) password2 = forms.CharField(label= 'تکرار رمز عبور', widget = forms.PasswordInput, strip = False) class Meta: model = User fields = ["username", "email", "password1", "password2"] views.py: def register(request): if request.method == "POST": form = UserFormRegistration(request.POST) if form.is_valid(): user =form.save() username = form.cleaned_data.get("username") login(request, user) messages.success(request, f"تبریک! اکانت شما با نام {username} با موفقیت ساخته شد") return redirect ("/") else: form = UserFormRegistration() return render(request, "accounts/registration.html", {"form":form}) So now, when i try to register with this form in the website i get some error like: The two password fields didn’t match. Enter a valid email address. The password is too similar to the username. How can i change these errors? For example i want to change the language and i don't want third error at all -
Using the URLconf defined in market.urls, Django tried these URL patterns
I am newbie in django. I am using DeleteView to delete the record from model but when I hit the delete button it's show me that error page not found (404) : Using the URLconf defined in market.urls, Django tried these URL patterns. I think the issue in urls.py file: from django.urls import path,include from stock.views import * from django.contrib.auth.decorators import login_required app_name='stock' urlpatterns = [ path('',login_required(StockView.as_view(), login_url='login'), name='stock'), path('login/', LoginView.as_view(), name='login'), path('signup/', SignupView.as_view(), name='signup'), path('logout',LogoutView.as_view(), name='logout'), path('addproduct/', login_required(AddProduct.as_view(), login_url='login'), name='addproduct'), path('update/<int:pk>', login_required(EditProduct.as_view(), login_url='login'), name='editproduct'), path('<int:product_id>/delete', login_required(DeleteProduct.as_view(), login_url='login'), name='deleteproduct'), ] views.py class DeleteProduct(DeleteView): model = Product success_url = reverse_lazy('stock:stock') template_name = 'stock/stock.html' Thank you! -
Django dont watch my app and TemplateDoesNotExist at /news
I think its this problem - django watching on mainApp but not on news app - django.template.loaders.app_directories.Loader: C:\Users\Name_User\Desktop\mysite\mainApp\templates\news\posts.html but i dont know how repair it, iam very new in django Directory of project ERROR TemplateDoesNotExist at /news news/posts.html, news/articles_list.html Request Method: GET Request URL: http://127.0.0.1:8000/news Django Version: 3.0.4 Exception Type: TemplateDoesNotExist Exception Value: news/posts.html, news/articles_list.html Exception Location: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py in select_template, line 47 Python Executable: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\Victor.INC\\Desktop\\mysite', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\south-1.0.2-py3.7.egg'] Server time: Sun, 29 Mar 2020 12:20:58 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\Desktop\mysite\mainApp\templates\news\posts.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\news\posts.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\templates\news\posts.html (Source does not exist) Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\Desktop\mysite\mainApp\templates\news\articles_list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\news\articles_list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\templates\news\articles_list.html (Source does not exist) Traceback Switch to copy-and-paste view C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py in _get_response response = response.render() … ▶ Local vars C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py in render self.content = self.rendered_content … ▶ Local vars C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py in rendered_content template = self.resolve_template(self.template_name) … ▶ Local vars C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py in resolve_template return select_template(template, using=self.using) … -
Heroku app having Mysql database on CleasDB very slow
I have uploaded my MySql data base to a ClearDb server since then, the website (which right now is running locally and is not uploaded yet ) is super slow! I even upgraded the ClearDb account by still , very slow does someone have a solution ? thanks -
How to Upgrade to the latest version of Django
The current version of python which is currently running in my system is 3.7.4 while the django is 1.11 due to which i recieve alots of errors , can someone explain how to Upgrade Django to the Latest version ?? -
Django transform lat lon models to one pointfield and serialize it via geojson
My model # GPS latitudes latitudine = models.FloatField(max_length=50,default=None) # GPS longitude longitudine = models.FloatField(max_length=50,default=None) # GEOJson point = models.PointField(srid=4326, geography=True, null=True) is there any way to create or pass lat long data to GEOjson model? "features": [ { "type": "Feature", "properties": { "latitudine": "45.0717383", "longitudine": "7.6810848" }, "geometry": null }, so all data from feature will go to geometry field? -
python manage.py makemigrations does not work on Heroku
The project runs fine on my localhost, but when I try to deploy iron Heroku, it does not detect the AbstracBase user model. It creates the Profile model but when I try to migrate the changes it throws a Makekigrations (venv) C:\Users\KIIT\Documents\Django\Touch>heroku run python manage.py makemigrations Running python manage.py makemigrations on ⬢ api-touch... up, run.1133 (Free) Migrations for 'account': account/migrations/0001_initial.py - Create model Profile Migrations for 'questions': questions/migrations/0001_initial.py - Create model Question Migrations for 'answers': answers/migrations/0001_initial.py - Create model Answer Migrate (venv) C:\Users\KIIT\Documents\Django\Touch>heroku run python manage.py migrate Running python manage.py migrate on ⬢ api-touch... up, run.7280 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 166, in check_key return self.graph.root_nodes(key[0])[0] IndexError: list index out of range During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 86, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, … -
django.docutils.six module not found in heroku
this is my firtime deploying to heroku cloud and when i deployed it wont just load, gunicorn and procfile everything is right. If someone can help to fix it, it will be so much appreciated. i think the error is related to django utils six whose provision was dropped fromdjango3 but dont know any way to fix that myself. 2020-03-29T12:01:12.508961+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 35, in load_middleware 2020-03-29T12:01:12.508961+00:00 app[web.1]: middleware = import_string(middleware_path) 2020-03-29T12:01:12.508961+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/module_loading.py", line 17, in import_string 2020-03-29T12:01:12.508962+00:00 app[web.1]: module = import_module(module_path) 2020-03-29T12:01:12.508962+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2020-03-29T12:01:12.508962+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-03-29T12:01:12.508963+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-03-29T12:01:12.508963+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load 2020-03-29T12:01:12.508963+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked 2020-03-29T12:01:12.508964+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked 2020-03-29T12:01:12.508964+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 678, in exec_module 2020-03-29T12:01:12.508964+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2020-03-29T12:01:12.508964+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/whitenoise/middleware.py", line 10, in <module> 2020-03-29T12:01:12.508965+00:00 app[web.1]: from django.utils.six.moves.urllib.parse import urlparse 2020-03-29T12:01:12.508971+00:00 app[web.1]: ModuleNotFoundError: No module named 'django.utils.six' 2020-03-29T12:01:12.509454+00:00 app[web.1]: [2020-03-29 12:01:12 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-03-29T12:01:12.638899+00:00 app[web.1]: [2020-03-29 12:01:12 +0000] [12] [ERROR] Exception in worker process 2020-03-29T12:01:12.638902+00:00 app[web.1]: Traceback (most … -
Django prefetch_related() in ListView class based view
I have a simple blog with 2 models: one for Post and one for Comment, like so: class Post(models.Model): title = models.CharField(max_length=100) # content = models.TextField() content = RichTextUploadingField(blank=True, null=True, config_name='claudiu_cfg') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): author = models.CharField(max_length=20) text = models.TextField(max_length=350) date_posted = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.author I want to display all posts (paginated) and how many comments each have. My views.py: class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 Just like this i was getting all posts, but now i want to access the Comment table with as little selects as possible. I know one way to do this is define a queryset and did it like this: class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 querryset = Post.objects.all().prefetch_related() However that does not access the Comment data. Then i tried to overrite the get_queryset() function hopping to get the desired result. Still no success. def get_queryset(self): posts = Post.objects.all().prefetch_related('pk__comment').all() comments = Comment.objects.all().prefetch_related('post') print(dir(posts)) print('---------------------') print(posts._prefetch_done) return posts.order_by('-date_posted') That still … -
iterating over <class 'django.http.request.QueryDict'>?
i am sending a post request via ajax to the django's backend. When i print the respnse using print(type(request.POST)) the output is () . now i want to type cast it in dictionary and then iterate through it. def checkoutnow(request): dict_items = {} p = 0 if request.method == 'POST': print(type(request.POST)) m = request.POST print(dict(m)) m = dict(m) print(m['object[0][name]']) print(len(m)) m.pop('csrfmiddlewaretoken') print(len(m)) for i in range(int(len(m)/5)): dict_items = {i : {'name':f"object[{i}][name]", 'qty': f"object[{i}][qty]"}} p = len(m)/5 print(dict_items) return render(request, "mart/checkout.html") when i typecasted it in dict()... the output is : {'object[0][name]': ['new5'], 'object[0][id]': ['5'], 'object[0][price]': ['888'], 'object[0][qty]': ['7'], 'object[0][category]': ['new arrival'], 'csrfmiddlewaretoken': ['lkPPM58fYxegavTCAz75mN5EiFvynjIr27khr78AYdQRIb49nhT4YFjcTuuVwlLb']} therefore i pop the last item and then iterate it using f string but the problem is with the output: {0: {'name': 'object[0][name]', 'qty': 'object[0][qty]'}} Looks like the keys that i am iterating via f strings are not putting the values...how can i iterate through it? -
Extending a ModelForm with a ForeignKey field that was previously excluded
I have the following model: class Watchman(models.Model): group = models.ForeignKey('groups.Group') name = models.CharField(max_length=64) And the following model form: class NewWatchmanForm(forms.ModelForm): class Meta: model = Watchman fields = ['name'] At the time the new Watchman is created, I do not know which group it belongs to, hence name is the only model field defined in NewWatchmanForm. However, once I do figure out the correct group it belongs to, I use this form to update the object with the appropriate group: class UpdateWatchmanForm(NewWatchmanForm): group = forms.ModelChoiceField(queryset=Group.objects.all()) class Meta(NewWatchmanForm.Meta): fields = NewWatchmanForm.Meta.fields + ("group",) I was curious if there might be a better way to reuse my NewWatchmanForm. Ideally, I'd like to avoid having to declare the group explicitly, something like this: class UpdateWatchmanForm(NewWatchmanForm): # group = forms.ModelChoiceField(queryset=Group.objects.all()) class Meta(NewWatchmanForm.Meta): fields = NewWatchmanForm.Meta.fields + ("group",) However, if I do that, I get this error: fields = NewWatchmanForm.Meta.fields + ("group",) TypeError: can only concatenate list (not "tuple") to list What is the correct way to subclass an existing ModelForm and include a ForeignKey field (without redefining forms.ModelChoiceField(...))? -
How to get current logged in user using django-microsoft-auth for Microsoft authentication?
I was following this guide to implement Microsoft authentication for my django app (https://django-microsoft-auth.readthedocs.io/en/latest/usage.html) using the django-microsoft-auth package. I just don't understand how I can get the currently logged in user id/email after the user has successfully logged in as the guide does not cover this? -
How to fix NoReverseMatch at /delete_order/1/
and always show this error: Reverse for 'delete_order' with arguments '('',)' not found. 1 pattern(s) tried: ['delete_order/(?P<pk>[0-9]+)/$'].whereas my urls.py file is given below my urls from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.Home, name = 'home'), path('products/', views.Products, name = 'products'), path('customers//', views.Customers, name = 'customers'), path('create_order//', views.CreateOrder, name = 'create_order'), path('update_order//', views.UpdateOrder, name='update_order'), path('delete_order//', views.deleteorder, name='delete_order'), ] create order file html {% extends 'accounts/main.html' %} {% load static %} {% block content %} {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{form}} {% endfor %} {% endblock %} my models which are given below from django.db import models class Customer(models.Model): name = models.CharField(max_length=100, null=True) phone = models.CharField(max_length=100, null=True) email = models.CharField(max_length=100, null=True) created_date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Tags(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('Outdoor', 'Outdoor') ) name = models.CharField(max_length=100, null=True) price = models.FloatField( null=True) category = models.CharField(max_length=100, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True) created_date = models.DateTimeField(auto_now_add=True, null=True) tags = models.ManyToManyField(Tags) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for Delivery', 'Out for Delivery'), ('Delivered', 'Delivered'), ) … -
Django ORM: adding counter for all subclasses to (abstract) parent class
I am working on a restaurant app. I have different dish type classes (Pizza, Platter, etc) and in order to pass a dict or list (JSON-format) of ALL dishes to the JS-client, I was thinking of adding an (abstract) parent class Dish that would contain a counter or ID that identifies every dish (the aim being I can then use those ID's to access a large number of input fields and respective IDs in the html-form from the menu-page). Any ideas on the best way to do this? I tried using InheritanceManager(), but that doesn't work if my Dish class is abstract. If it is not abstract (which it should be, I'd say), I get a You are trying to add a non-nullable field 'dish_ptr' error. Not sure my whole approach even makes sense, but can't think of a better way to work with large HTML-forms with 50-100 input fields (menu items). -
Celery - No result backend is configured
Im currently unable to make celery using redis as a results backend as i want some of my tasks wait to finish before accepting the next one. The Problem now seems that celery does not recognize the results backend for some reason. celery.py import... os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'App.settings') app = Celery(str(settings.SITE_NAME), broker=str("redis://") + env.str('REDIS_HOST') + ":" + env.str('REDIS_PORT')) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": [ str("redis://") + env.str('REDIS_HOST') + ":" + env.str('REDIS_PORT') + str("/") + env.str('REDIS_CACHE_DB') ], "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "SOCKET_CONNECT_TIMEOUT": 30, # in seconds "SOCKET_TIMEOUT": 30, # in seconds "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", "CONNECTION_POOL_KWARGS": {"max_connections": env.int('REDIS_MAX_CONN'), "retry_on_timeout": True} } } } # Celery Settings: BROKER_URL = str("redis://") + env.str('REDIS_HOST') + str(":") + env.str('REDIS_PORT') CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'default' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'GMT' CELERYD_TASK_SOFT_TIME_LIMIT = 300 with this settings in place I get the following error: No result backend is … -
Implementing Vue RESTful API calls in Django within Django Templates with Session Authentication
I have a Django project that requires page refreshes any time I want to update the content. Currently it uses the built in Django Class Based Views, which in turn use Templates. I want to start implementing some javascript calls to refresh tables/forms/modal windows with new data, mostly in response to button clicks. I'm trying to use Vue to accomplish this, and I have created a Django REST Framework backend to facilitate this. I got a simple 'Hello world' vue class working where the data is hard coded into the data field of the Vue class. I can't seem to make the jump to getting data from the API though. I am getting an Unauthorized response. I have unit tests where I call the API from the DRF APITestCase using the self.client.get('api/path') and they work as expected (unauthorized when there is no authenticated user attached to request, authorized when there is). I have debugged into the DRF Permission class to see why the request is being refused and it is because there is no authenticated User attached to the request. I have added SessionAuthentication to the DEFAULT_AUTHENTICATION_CLASSES in settings. My question is, how do I add an authenticated user to … -
Route to different databases depending on the group of users in Django Rest Framework
I have a project with Django rest framework as backend and Vue as frontend and everything works well. Now, I have to extend my project. I want to bring the same product, but to a new group of users, who will have 0 interaction with the first group of users. No data will be shared among the two groups of users. Like if I created a copy of my backend with a new database and directed the new group of users to this new backend. So, I am looking for a solution not to have to build another backend for each new independent group of users (which is obviously less than ideal). I could create permissions where users could only access data about their own group and change every querysets. But I think it is not optimal to keep everyone on the same table as the number of groups of users will grow. I guess the ideal would be to have 1 database per group of users, 1 backend in total, and to route users to their own group specified by the api call they make with a /groupID/rest-of-endpoint Is that possible in Django ? Do you see any solution … -
Facing a probelm to find source code of generic views
I am searching source code of generic views - listView - UpdateView - TemplateView - DeleteView but i am not able to find in documentation. Kindly someone share the link where i can see the source code of these views. Thank you! -
How to render aut generated listed to django template
maybe my question is silly but this is giving me a headache. let's say that: list_1 =[1,2,3,4,...] new_dic ={} for i in list_1: new_dic[i] = [] How to render new_list[1] , new_list[2] .... automatically on Django? -
duplicated lines are fetched by filter
I have a little bit complex combination of | & filter like this. objs = objs.annotate(num_line=Count("lns")).filter(Q(lns__id__in=lnIds) | (Q(sts__id__in=oIds) & (Q(lns__id__in=lnIds) | Q(num_ln__lte=0)))) It looks like work, but results are sometimes deplicated (has same id). id 1 2 3 3 4 5 I thought filter is assured to return unique id though ,am I wrong?? Or is it possible to omit duplicated rows?? class Obj(models.Model): created_at = models.DateTimeField(null=True) lns = models.ManyToManyField(Ln) sts = models.ManyToManyField(St) is = models.ManyToManyField(Is) pub_date = models.DateTimeField('date published') -
django serialize json in geojson
i have a model like: latitudine = models.FloatField(max_length=50,default=None) longitudine = models.FloatField(max_length=50,default=None) and I need to serialize it and send it in geojson format I'm using usual django json serializer in view: def meterpoints(request): points = serialize('json', Contatore.objects.all(),fields='latitudine, longitudine') return HttpResponse(points, content_type='json') what I receive is: { "model": "conlet.contatore", "pk": "1012-081-7217", "fields": { "latitudine": "45.0717383", "longitudine": "7.6810848" } } so, is there any way to serialize my model in geojson creating a pointfiled from my lat long model, so leaflet can understand it? -
How to connect websocket after set up with NGINX and Supervisor?
I created a Django Channel beside my wsgi application. Everything works fine if I run: daphne -b 0.0.0.0 -p 8001 myapp.asgi:application I can connect to the websocekt but after I created supervisor with nginx I can not connect and I don't see any useful log that could solve the problem. When I check the supervisor status it has no error: asgi:asgi0 RUNNING pid 23981, uptime 0:10:22 asgi:asgi1 RUNNING pid 23980, uptime 0:10:22 asgi:asgi2 RUNNING pid 23983, uptime 0:10:22 asgi:asgi3 RUNNING pid 23982, uptime 0:10:22 The socket was originally localhost:8001 and I also allowed UFW to use that port but it didn't work so I changed to my server IP. Supervisor [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://139.162.172.87:8001 # Directory where your site's project files are located directory=/home/markkiraly/crumb_backend # Each process needs to have a separate socket file, so we use process_num # Make sure to update "mysite.asgi" to match your project name command=/home/markkiraly/crumb_backend/venv/bin/daphne --fd 0 --access-log - --proxy-headers crumb_backend.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=4 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose …