Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirect Reverse to specific view with arguments
In the same app, I have a form that can be rendered and processed in two different views. The url for the views are defined as following: app_name = 'table' urlpatterns = [ path('<int:table_pk>/order/', include([ path('', views.table_detail_category_view, name='table_detail_category_view'), path('<str:menu_category>/', views.table_detail_item_view, name='table_detail_item_view'), ])), ] The processing of the form, however, is implemented in only one of the views (for eg. table_detail_category_view) since it is redundant to implement one more time (one for each view). After processing the form, I have to redirect the page to whatever view that was displayed before. Specifically, I am looking for something like this: if request.method == 'POST': ...process form... if previous_view = table_detail_category_view: return redirect(reverse('table:table_detail_category_view', args=(table_pk,))) else: if previous_view = table_detail_item_view: return redirect(reverse('table:table_detail_item_view', args=(table_pk, category,))) The variables table_pk and category are present in both views. I am trying to avoid implementing the form-processing twice (one in each view) in order to redirect reverse to the appropriate view. That method does not seem DRY. Thanks. -
How to use async with Mutation in Django-graphene
I have a problem, where I want to optimise a client call to a mutation in a GraphQL API. The mutation executes 2 methods, where one is slow and where the result does not need to be send back to the client. I have tried to look at Django signals to handle this, but since signals are executed in sync, there is no benefit. Also, using Django signal request_finished seems not possible, because the method I need to execute needs to access model instance. So my question is this. Lets say I have a Django Model and I have two methods I use in a mutation. class My_model(models.Model): some_field = models.CharField() def some_method(): return "do something" def some_other_method(): return "do something else" Now I have a mutation like the one below, where I do not want the client to wait for the execution of the method My_model.some_other_method() class CreateTwoObjects(graphene.Mutation): result = graphene.String() def mutate(self, info, input): result = My_model.some_method() # method to not wait for My_model.some_other_method() return CreateTwoObjects(result = result) Is there a way I can execute this method in async and not have client wait for the return? -
Displaying only linked tags Django Admin
i have product tag and its variations of tag example: Color|green Quality|bad i need to display only linked variations when i create product i need to display only colors when i choice color models.py class Variety(models.Model): varietyName = models.CharField(max_length=30) def __str__(self): return self.varietyName class Meta: verbose_name = "List variations" class Tag(models.Model): STATUS_VARIETY=( ('Filters', 'Filter'), ('Variaty', 'Variaty'), ('Boths', 'Boths'), ) status = models.CharField(max_length=10, choices=STATUS_VARIETY, default='Boths', verbose_name='status') name = models.CharField(max_length=255, verbose_name='name') variety = models.ManyToManyField(Variety, related_name='children', verbose_name='Parent') def __str__(self): return self.name class Meta: verbose_name = "Variation" verbose_name_plural = "Variations" class Productcopy(models.Model): STATUS_PRODUCT=( ('Publish', 'Publish'), ('Not_to_publish', 'Not_to_publish'), ) status = models.CharField(max_length=30, choices=STATUS_PRODUCT, verbose_name='status') name = models.CharField(max_length=100, verbose_name='name') tag = models.ForeignKey(Tag, verbose_name='Variation', on_delete=models.CASCADE) variety = models.ManyToManyField(Variety, verbose_name='Variations') def __str__(self): return self.name class Meta: verbose_name = "product" verbose_name_plural = "products" admin.py from .models import * class TagAdmin(admin.ModelAdmin): list_display = ('name', 'status',) filter_horizontal = ('variety',) class ProductcopyAdmin(admin.ModelAdmin): list_display = ('name', 'status',) filter_horizontal = ('variety',) admin.site.register(Tag,TagAdmin) admin.site.register(Productcopy,ProductcopyAdmin) admin.site.register(Variety) -
Django on Apache2: Issue in.conf-file?
Good day to all of you, together with our admin in our company, we're trying to deploy Django on Apache2 together with mod_wsgi, but we're facing some minor issues. I'm hoping, some of you might help and take a look at the following lines!? Right now, the directory on our server is looking like this: ./var/www/ |-- myproject |-- manage.py |-- project/ |-- __init__.py |-- settings.py |-- urls.py |-- wsgi.py |-- statics |-- venv When I'm trying to open the site, it just keeps on loading but nothings gonna happen! I'm wondering wether the data inside our .conf-file might be wrong! <VirtualHost *:80> . . . Alias /static /var/www/myproject/static <Directory /var/www/myproject/static> Require all granted </Directory> <Directory /var/www/myproject/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/var/www/myproject python-home=/var/www/myproject/venv WSGIProcessGroup myproject WSGIScriptAlias / /var/www/myproject/project/wsgi.py </VirtualHost> If I understood it correctly, the "python-home" inside the "WSGIDaemonProcess" should point onto my Virtual Environment to collect the necessary components and the "python-path" onto my project!? I also noticed, that the current running python-version on the server is 2.7.6, although my admin installed version 3.7. The installed mod_wsgi is "libapache2-mod-wsgi-py3" for python 3x! Could this also be a problem? Thanks and a great day to … -
In S3 Bucket CORS Configrations not allowing xml and asking for json instead
In S3 Bucket CORS Configrations not allowing "XML" and asking for "Json" instead <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> Was Working earlier but now it is giving me this error "The CORS configuration must be written in valid JSON." Some Changes are made in "Amazon S3 Bucket" by AMAZON , Please give me json of this to add in CORS ? -
Djnago 'ImageFieldFile' object has no attribute '_meta'
Actually i'm trying to update user profile but when i try to update it it show's the error. AttributeError at /user/profile/ 'ImageFieldFile' object has no attribute '_meta' After searching so many solution i can't get rid of it. I am messing with my code from 24hrs. Please help me to get rid of this. -- My code is --- Views.py @login_required() def profile(request): if request.method=='POST': u_form = UserUpdateForm(request.POST,instance=request.user) p_form = ProfilePicUpdateForm(request.POST,request.FILES,instance=request.user.profile_image) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Account Created Successfully for {username}') redirect('profile/') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfilePicUpdateForm() context = {'u_form': u_form,'p_form':p_form} return render(request,'profile.html',context) Forms.py class UserUpdateForm(forms.ModelForm): username = forms.CharField() email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = KeepSafeUserModel fields = ['username','email','first_name','last_name'] class ProfilePicUpdateForm(forms.ModelForm): class Meta: model = KeepSafeUserModel fields = ['profile_image'] Models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # ///////////////User Manager///////////////////// # Create your models here. # overriding the create and superuser function class MyAccountManager(BaseUserManager): def create_user(self,email,username,password=None): if not email: raise ValueError("Users Must Have email Address") if not username: raise ValueError("Users Must Have username") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password): user = self.create_user( email = self.normalize_email(email), … -
Foreign key value in Django REST Framework Datatables
I followed this SOF question Foreign key value in Django REST Framework closely and many others plus read this documentation and similar multiple times https://datatables.net/manual/tech-notes/4 but have yet to find a solution. Error message: DataTables warning: table id=entrytable - Requested unknown parameter 'symbol' for row 0, column 9. For more information about this error, please see http://datatables.net/tn/4 However, the right symbol.name does work in the end when I click okay on the error message.. I've tried to find a solution for this error for the past 2 days and not sure what else to try. If I comment out: # symbol = serializers.CharField(source='symbol.name', read_only=True) Then the serializer will show just the foreign key but no error message. Seems to be an issue in my datatables javascript now. However, I've tried their suggestions and still no luck. serializers.py (Everything commented out in serializers.py are attempted solutions) class EntrySerializer(serializers.ModelSerializer): symbol = serializers.CharField(source='symbol.name', read_only=True) # symbol = serializers.SerializerMethodField('get_symbol_name') # # def get_symbol_name(self, obj): # return obj.symbol.name class Meta: model = Entry # fields = ('id', 'date', 'amount', 'price', 'fee', 'entry_type', 'reg_fee', 'transaction_id', 'trade', 'symbol', 'created_by') fields = '__all__' # depth = 1 entry_list.html {% extends "dashboard/base.html" %} {% load i18n %} {% block … -
Deploy Django project to Ubuntu + Apache + mod_wsgi
Please please please help me. I've followed this tutorial and this one and this one and this but still can't make it work. I have a VM from DigitalOcean with Apache and mod_wsgi. My Django project is stored in /var/www/mydomain.com. It is nothing fancy, just a Hello World. All I want is to run that with mod_wsgi in Daemon mode. Please tell me what should I put in my config file? All those tutorials I read provide a different approach and none of them worked for me. At best, I got the famous index of showing the content of the folder. So I removed everything. In fact I destroyed my droplet and now its a fresh install of Ubuntu 20.04. Apache is installed and works. Here's the config file if it matters: <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName mydomain.com ServerAlias www.mydomain.com DocumentRoot /var/www/mydomain.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =mydomain.com [OR] RewriteCond %{SERVER_NAME} =www.mydomain.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> The last 4 lines are added by certbot to redirect http to https, and it works fine. -
Django version 3.1.3 form not saving to model
I am following this tutorial I have gone back and written the code to match exactly. I have another form that works called category_add which is exactly the same as this form. But for the life of me I cannot figure out why bookmark_add doesn't update the database with the form entries. Models.py from django.db import models from django.contrib.auth.models import User class Category(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) created_by = models.ForeignKey(User, related_name='categories', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.title class Bookmark(models.Model): category = models.ForeignKey(Category, related_name='bookmarks', on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) url = models.CharField(max_length=255, blank=True) created_by = models.ForeignKey(User, related_name='bookmarks', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title View.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import BookmarkForm @login_required def bookmark_add(request, category_id): if request.method == 'POST': form = BookmarkForm(request.POST) if form.is_valid(): bookmark = form.save(commit=False) bookmark.created_by = request.user bookmark.category_id = category_id bookmark.save() return redirect('category', category_id=category_id) else: form = BookmarkForm() context = { 'form': form } return render(request, 'bookmark/bookmark_add.html', context) Forms.py from django.forms import ModelForm from .models import Bookmark class BookmarkForm(ModelForm): class Meta: model = Bookmark fields = ['title', 'description', 'url'] Urls.py path('', dashboard, name='dashboard'), path('categories/', categories, name='categories'), path('categories/add/', … -
Django Filling an Empty Query Set
In my Django Application, I have printed a list of query's. the first query set contains the followers of the current logged in user, The second is an empty query set, and the last printed items are a list of queries each containing the profile objects of each of those followers indicated in the first printed query. Is there a way to fill the empty query set in the middle with the list of profile object query sets, but all in one ( similar to the format of the first printed query set) -thank you for taking the time to read my questionenter image description here -
whats the best possible way to sort here
In my django app i have an import model where i have FOR_COUNT as a field and VALUE as another field in my views i am trying to show top five countries(countries with highest values) and all the remaining countries as one entity i.e others. What will be the best possible way to do this, i think sorting of some kind will work here, but am fairly new with django. Country = Import.objects.order_by('FOR_COUNT').values('FOR_COUNT').distinct() result = [] for val in Country: Info = Import.objects.filter(FOR_COUNT=val['FOR_COUNT']).filter(Date__year=year) TotalValue = Info.aggregate(Sum('VALUE')) result.append({ "label" : val['FOR_COUNT'], "value" : 0 if TotalValue['VALUE__sum'] is None else TotalValue['VALUE__sum'] }) return_data.update({ "topCounty" : result }) -
Django Rest Framework logic
My project receives a POST with a string and then I want to run a function that may take several seconds to finish on that query and update the model with the result. Currently I'm using Django Rest Framework to create an API that creates the model from the POST request and I put the function call within the views.py as so: def post(self, request, format=None): serializer = SearchSerializer(data=request.data) if serializer.is_valid(): query = serializer.validated_data.get('query') # I would expect ProteinSearch.search(query) to take a long time protein_search = ProteinSearch.search(query) serializer.save(**protein_search) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This clearly is blocking at the moment. My question is, do I have this in the right place and should be using some type of concurrency such as threads or is this incorrectly placed in views? -
Unresolved Reference in Pycharm Using Django
code I'm using Pycharm. I created a new app called pages that's part of this tutorial on Youtube. I created some functions in the pages/views.py. Then I went to urls.py to import the functions and add the URLs. But the IDE can't find pages. I tried restarting Pycharm/invalidating the caches, and that did not work. Please let me know if you have any ideas. -
Django not running on localhost when using with Docker
I am a beginner to web development with Django. I have been trying to use docker-compose as a part of the lectures but due to some issues, I am not able to run the server. This is my docker-compose.yml file: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=1029384756Vithayathil ports: - "5432:5432" migration: build: . command: python3 manage.py migrate volumes: - .:/usr/src/app depends_on: - db web: build: . command: python3 manage.py runserver volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db - migration This is my DockerFile: FROM python:3 WORKDIR /usr/src/app ADD requirements.txt /usr/src/app RUN pip install -r requirements.txt ADD . /usr/src/app This is my database in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PASSWORD':'**********', 'PORT': 5432, } } On doing docker-compose up command, these things happen: Starting airline4_db_1 ... done Starting airline4_migration_1 ... done Starting airline4_web_1 ... done Attaching to airline4_db_1, airline4_migration_1, airline4_web_1 db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2020-11-07 15:37:00.770 UTC [1] LOG: starting PostgreSQL 13.0 (Debian 13.0-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit db_1 | 2020-11-07 15:37:00.789 UTC [1] LOG: listening … -
How to Solve a FieldError- Cannot resolve keyword 'slug' into field
I'm making a Post and Comment model. I created and Post and Comment model and it looks ok. I can add post and also comment to any particular post. But getting trouble when I'm trying to delete the comment after several attempts I am getting an error from test_func. Here is the views.py class PostCommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment template_name = 'blog/postcomment_confirm_delete.html' # <app>/<model>_<viewtype>.html def test_func(self): comment = self.get_object() <------------- Error showing from here if self.request.user == comment.user: return True return False def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug'])) Here is the template: {% for comment in comments %} <ul class="list-unstyled"> <li class="media"> <img class="rounded-circle article-img" src="{{ comment.post.author.profile.image.url }}"> <div class="media-body"> <h5 class="mt-0 mb-1">{{comment.user| capfirst}}<small class="text-muted">- {{ comment.created}}</small> </h5> <hr class="solid mt-0"> {{ comment.content}} </div> </li> </ul> {% if comment.user == user %} <div> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'blog:post-commentu' post.slug %}">Update</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'blog:post-commentd' post.slug %}">Delete</a> </div> {% endif %} {% endfor %} Here is the url path('blog/<slug:slug>/delete_comment/', PostCommentDeleteView.as_view(), name='post-commentd'), Here is the models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = RichTextUploadingField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') slug = models.SlugField(blank=True, null=True, max_length=120) class Comment(models.Model): … -
How do I go about debugging 'OSError: Failed to write data' on my Flask server?
I'm running a Flask application (with some bits of Django ORM) on Elastic Beanstalk (code link: https://github.com/onnela-lab/beiwe-backend). However, I'm getting constant notifications from Elastic Beanstalk about 5xx failures (~5-25% failures). Looking at the logs (/var/logs/httpd/error_log), I see the following errors: Error 1: [Fri Nov 13 13:58:55.487007 2020] [:error] [pid 14630] [remote {load_balancer_ip_address:port1}] mod_wsgi (pid=14630): Exception occurred processing WSGI script '/opt/python/current/app/wsgi.py'. [Fri Nov 13 13:58:55.487070 2020] [:error] [pid 14630] [remote {load_balancer_ip_address:port1}] OSError: failed to write data Error 2: [Fri Nov 13 13:59:55.486449 2020] [:error] [pid 17765] (70008)Partial results are valid but processing is incomplete: [client {load_balancer_ip_address:port2}] mod_wsgi (pid=17765): Unable to get bucket brigade for request Doing a quick grep -c (result: 5418) for each of these confirms that they're likely related issues, despite no correlation in PIDs and different LB ports. I did some research on Stack Overflow and found the following related questions: Django OSError: failed to write data Apache + mod_wsgi + flask app: "Unable to get bucket brigade for request" error in logs Summary: It's possible that clients with spotty connections are causing this issue due to an interrupted connection or that something is killing the Apache child worker process. Most of the clients calling this API are … -
Serve some static from Django and others from s3
I have a Django app on Heroku and recently moved all my static files to s3. This is working great, except a few static files used in a script that need to be served locally. I'm using the https://github.com/higuma/web-audio-recorder-js to let the visitor leave a voicemail. When the files are on S3, I get this error when leaving a voicemail: gum_error err.name: SecurityError; SecurityError: Failed to construct 'Worker': Script at '[my-s3-bucket]' cannot be accessed from origin '[my-domain]'. From this SO answer, it seems "Chrome doesn't let you load web workers when running scripts from a local file." So I think to solve this, I need to serve most of my static files on S3, but a few of them locally. I'm using django-storages and boto3 for static files, and it seems like it's all-or-nothing. -
How to grab context from Django Generic Views
I'm very new to django and I'm trying to override the get_context method but it's not working for me Views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): context = super(PostCreateView, self).get_context_data(**kwargs) context['content'] = self.content return context models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() 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}) -
Using GET parameters with Django and Ionic
I'm developing an application where I need to make HTTP requests, so I'm trying to use the GET method with parameters. My code in ionic is this: getZona(code: string) { return this.http.get( this.API_URL + "zonas", {codigo_acceso: code}, {} ); } My Django code is class ZonaView(viewsets.ModelViewSet): queryset = Zona.objects.all() serializer_class = ZonaSerializer So when I do a GET request, I get all records, even though if the parameter's value doesn't exists in the records. No matter what I write in the parameter, I get all records. I have tried with postman and I get the same behavior. Hope you can help me. -
Can I use an aggregation function on the result of a previous aggregation function in Django?
I've been receiving the following error on a query: Cannot compute Sum('failures'): 'failures' is an aggregate I have a model that represents a payment: class Payment(models.Model): created = models.DateTimeField(null=True) customer_name = models.CharField(max_length=50) status = models.CharField(max_length=20) # e.g. 'paid' or 'failed' When an user makes a purchase and tries to perform payment with her credit card, a Payment object is created. If the attempt fails, the status becomes 'failed'. An user may try several times, generating several Payment objects with the 'failed' status, and then give up, or maybe when she tried with a different card the nth payment was successful. I would like to perform an aggregated query where I can count both the total number of failed attempts and the "unique" fails, that is, counting a single fail for each customer that had a failed attempt. For example, suppose we had the following payment attempts Date/Time Customer Name Status 2020-11-10 8:00a.m Alice failed 2020-11-10 8:01a.m Alice failed 2020-11-10 8:02a.m Alice failed 2020-11-10 8:10a.m Bob failed 2020-11-10 8:11a.m Bob paid 2020-11-11 7:30a.m Charles failed 2020-11-11 7:31a.m Charles failed I would like to obtain the following result using a queryset: Date Total failures unique failures 2020-11-10 4 2 2020-11-11 2 1 … -
Django Rest Framework Serializer Method Calling
I'm new at Django Rest Framework and I wonder how methods create and update are called inside a ModelSerializer Class. What I understand is that create and update methods are automatically triggered when a POST or PUT request is sent. Is there a way to call a new function, like say_hello()? Here's an example. I want to call method say_hello() when I hit a PUT Request class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" class Meta: model = User fields = "__all__" def create(self, validated_data): """Create a new user with encrypted password and return it""" return get_user_model().objects.create_user(**validated_data) def update(self, instance, validated_data): """Update an user, setting the password and return it""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user def say_hello(self, validated_data): print(validated_data) return "Hello you" -
Is there a way to add multiple models to a class view (django)?
I'm trying to add two models to a group update view so that when a new group is created the user gets added the the groups userList. This is what I have (the relevant stuff): allgroups\models.py class Allgroups(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) private = models.BooleanField(default=False) discussion = models.CharField(max_length=255) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('allgroups_detail', args=[str(self.id)]) class userlist(models.Model): allgroups = models.ForeignKey( Allgroups, on_delete=models.CASCADE, related_name = 'userList', ) user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return str(self.user) allgroups\views.py from .models import Allgroups, userlist, class AllgroupsCreateView(LoginRequiredMixin, CreateView): model = Allgroups template_name = 'allgroups_new.html' fields = ('title', 'body','private',) login_url = 'login' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class userlistUpdateView(CreateView): model = userlist fields = ('user','allgroups',) template_name = 'userlist_update.html' success_url = reverse_lazy('allgroups_list') def test_func(self): obj = self.get_object() return obj.author == self.request.user For the AllgroupsCreateView class I want to be able to use two models: model = Allgroups, userlist so that when the new group is created the author of the new group is added to the userlist Any ideas? Thanks! -
Django - Move url.py dispatcher to project folder
Newbie here ... Django Version:3.1.3 I want to put my urls.py dispatcher inside my project folder and not in the default application one for better visibility. Example: Project Name: Project Default Application Name: Project/Project So I would like to get the following: /urls.py I tried with a modification of /Project/settings but it doesn't work: ROOT_URLCONF = '.urls' My folder tree: . ├── env │ ├── bin │ ├── include │ ├── lib │ ├── lib64 -> lib │ ├── pyvenv.cfg │ └── share └── Project ├── __pycache__ ├── db.sqlite3 ├── manage.py ├── polls ├── Project └── urls.py -
How to make server for mobile app using Python and Django frameworks?
I doing mobile voice assistant and i need server side and client side but i dont know how writing this on Django or on some other framework python. How do you help me? -
Django HttpResponseRedirect versus redirect
Given the following: def add(request): if request.method == "POST": task = request.POST.get('task') form = NewTaskForm(request.POST) if form.is_valid(): task = form.cleaned_data["task"] request.session['tasks'] += [task] # return HttpResponseRedirect(reverse("tasks:index")) return redirect('tasks:index') else: return render(request, "tasks/add.html",{ "form": form }) return render(request, "tasks/add.html",{ "form": NewTaskForm() }) what's the difference, why would you use one over the other, between: return HttpResponseRedirect(reverse("tasks:index")) and: return redirect('tasks:index')