Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
multiple collapse items that call one django view function, each should submit a different value
I have multiple collapse items. all items should call the same django function while submitting a different value each. I want to achieve this without using django forms dropdown menu. what changes should I make to the current HTML code: HTML: <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Filter Options:</h6> <a class="collapse-item" value='1' href={% url 'show_dashboard' %}>Option1</a> <a class="collapse-item" value='2' href={% url 'show_dashboard' %}>Option2</a> <a class="collapse-item" value='3' href={% url 'show_dashboard' %}>Option3</a> <a class="collapse-item" value='4' href={% url 'show_dashboard' %}>Option4</a> <a class="collapse-item" value='5' href={% url 'show_dashboard' %}>Option5</a> <a class="collapse-item" value='6' href={% url 'show_dashboard' %}>Option6</a> <a class="collapse-item" value='7' href={% url 'show_dashboard' %}>Option7</a> </div> </div> -
Django Particular wise total in their respective rows
I am trying to print a particular wise total in the invoice using Django. The problem is if I use for loop, it prints the last items particular wise total in everywhere. I am confused what will be the best way to calculate individual total in their respective rows? Here is my Views.py: def order_complete(request): order_number = request.GET.get('order_number') transID = request.GET.get('payment_id') try: order = Order.objects.get(order_number=order_number, is_ordered=True) ordered_products = OrderProduct.objects.filter(order_id = order.id) total=0 subtotal = 0 for i in ordered_products: total = i.product_price * i.quantity subtotal += total payment = Payment.objects.get(payment_id = transID) context ={ 'order': order, 'ordered_products': ordered_products, 'order_number': order.order_number, 'transID': payment.payment_id, 'payment': payment, 'subtotal': subtotal, 'total':total, } return render(request, 'orders/order_complete.html', context) except(Payment.DoesNotExist, Order.DoesNotExist): return redirect('home') models.py class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, null=True) user = models.ForeignKey(Account, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) variations = models.ManyToManyField(Variation, blank=True) quantity = models.IntegerField() product_price = models.FloatField() ordered = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.product.product_name template <dd class="text-right">${{ total }}</dd> suggestion/solutions would be highly appreciated. Here is the result -
cannot send socket messages outside Consumer in Django views or somewhere
from the title shown I am not able to send socket messages here is my code class ChatConsumer(JsonWebsocketConsumer): _user = None @property def cu_user(self): try: self.user = self.scope['user'] self._user = User.objects.get(id=self.user.id) except User.DoesNotExist as e: print(e) return self._user def connect(self): # Join users group async_to_sync(self.channel_layer.group_add)( 'users', self.channel_name ) self.accept() def disconnect(self, close_code): # Leave app async_to_sync(self.channel_layer.group_discard)( 'users', self.channel_name ) self.close() # Receive json message from WebSocket def receive_json(self, content, **kwargs): if content.get('command') == 'chat_handshake': self._handshake(content) elif content.get('command') == 'user_handshake': self.user_handshake() def _handshake(self, data): """ Called by receive_json when someone sent a join command. """ logger.info("ChatConsumer: join_chat: %s" % str(data.get('chat_id'))) try: chat = "%s_%s" % (data.get('chat_type'), data.get('chat_id')) except ClientError as e: return self.handle_client_error(e) # Add them to the group so they get room messages self.channel_layer.group_add( chat, self.channel_name, ) # Instruct their client to finish opening the room self.send_json({ 'command': 'chat_handshake', 'chat_id': str(data.get('chat_id')), 'user': str(self.cu_user), }) # Notify the group that someone joined self.channel_layer.group_send( chat, { "command": "chat_handshake", "user": self.cu_user, } ) def user_handshake(self): key = f'user_{self.cu_user.id}' self.channel_layer.group_add( key, self.channel_name ) self.send_json({ 'command': 'user_handshake', 'user': str(self.cu_user) }) self.channel_layer.group_send( key, { 'command': 'user_handshake', 'user': str(self.cu_user) } ) # this is not working def send_socket(self, event): logger.info(event) print(event) self.send(text_data=json.dumps(event['message'])) I have written my code … -
I am not getting the value from the database
I am using MVT in django. I am using generic CBV (listview, detailview). here are my codes Here is model.py from django.db import models class Singers(models.Model): name= models.CharField(max_length=256) age= models.IntegerField() gender= models.CharField(max_length=10) class Albums(models.Model): name= models.CharField(max_length=256) singer=models.ForeignKey(Singers, on_delete=models.CASCADE) view.py from django.views import generic from core.models import Albums, Singers #in generic view instead of functions, we use classes class AlbumView(generic.ListView): model = Albums template_name = 'index.html' paginate_by = 10 def get_queryset(self): return Albums.objects.all() class DetailView(generic.DetailView): model = Albums template_name = 'detailview.html' Here are urls.py from django.urls import path from core.views import AlbumView, DetailView urlpatterns = [ path('album/', AlbumView.as_view()), path('album/detail/<pk>/', DetailView.as_view()) ] Here is index.html {% block content %} <h2>Albums</h2> <ul> {% for albums in object_list %} <li>{{ albums.name }}</li> {% endfor %} </ul> {% endblock %} here is detailview.html {% block content %} <h1>name: {{Albums.name}}</h1> <p><strong>Singer: {{Albums.Singer}}</strong></p> {% endblock %} The detail view is not working fine. It is not fetching the respective name of the album and singer details. Suggest me what should i do? -
How can I overwrite a models.py entry only if the user id is the current user?
I have genome files, and I want each user to be able to upload their own genome file, but they can only have one of them. I want it so that if they try to upload another, then they will just replace the genome and form data for their last entry. I am using their entries, along with n number of people who use the site (each person also having 1 entry per person) as samples to analyze against that person's genome, so I want to keep a models file full of genomes, names, sex, etc... but only one per user. Here's my models.py file from django.db import models from django.core.exceptions import ObjectDoesNotExist SEX_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) class Genome(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) CHOICES = [('M','Male'),('F','Female')] sex = models.CharField(max_length=1, choices=SEX_CHOICES, default='M') genome = models.FileField(upload_to='users/genomes/') #id = request.user.id #if id is the current user then replace old data with new data def __str__(self): return self.title and here is my views function def upload(request): context = {} if request.method == 'POST': form = GenomeForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('My-DNA.html') else: form = GenomeForm() return render(request, 'my-DNA.html', {context}) else: print("failure") form = GenomeForm() return render(request, 'Upload.html', … -
Access Foreignkey Instance on Function based Views Django
on Django, I tried to get photos instance on view but not with input parameter because this page has multiple forms, so I try to get photo instance automatically added when I post a comment in recent photos, but I have trouble getting photo instance id on views? everybody can help me? -
django remove m2m instance when there are no more relations
In case we had the model: class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): publications = models.ManyToManyField(Publication) According to: https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_many/, to create an object we must have both objects saved before we can create the relation: p1 = Publication(title='The Python Journal') p1.save() a1 = Article(headline='Django lets you build web apps easily') a1.save() a1.publications.add(p1) Now, if we called delete in either of those objects the object would be removed from the DB along with the relation between both objects. Up until this point I understand. But is there any way of doing that, if an Article is removed, then, all the Publications that are not related to any Article will be deleted from the DB too? Or the only way to achieve that is to query first all the Articles and then iterate through them like: to_delete = [] qset = a1.publications.all() for publication in qset: if publication.article_set.count() == 1: to_delete(publication.id) a1.delete() Publications.filter(id__in=to_delete).delete() But this has lots of problems, specially a concurrency one, since it might be that a publication gets used by another article between the call to .count() and publication.delete(). Is there any way of doing this automatically, like doing a "conditional" on_delete=models.CASCADE when creating the model or something? Thanks! -
Cannot import model from .models file to nested app sub_directory
Here is my project tree: (base) justinbenfit@MacBook-Pro-3 cds_website % tree . ├── api │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── serializers.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── admin.py │ ├── apps.py │ ├── main.py │ ├── management │ │ ├── __init__.py │ │ ├── commands │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ └── private.cpython-39.pyc │ │ │ ├── private.py │ │ │ └── scrape.py │ │ └── test.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ ├── 0001_initial.cpython-38.pyc │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── cds_website │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py └── requirements.txt api is an app in a greater project called cds_website. The settings.py file in cds_website project directory contains the following installed apps: INSTALLED_APPS = [ … -
How to create seperate POST request for imagefield in DRF
I need to make seperate api for imagefile. How can I acieve this??? models.py class Organization(models.Model): code = models.CharField(max_length=25, null=False, unique=True) name = models.CharField(max_length=100, null=False) location = models.ForeignKey(Location, on_delete=models.RESTRICT) description = models.TextField() total_of_visas = models.IntegerField(null=False, default=0) base_currency = models.ForeignKey(Currency, on_delete=models.RESTRICT) logo_filename = models.ImageField(upload_to='uploads/') serializers.py class OrganizationSerializer(serializers.ModelSerializer): location = serializers.CharField(read_only=True, source="location.name") base_currency = serializers.CharField(read_only=True, source="base_currency.currency_master") location_id = serializers.IntegerField(write_only=True, source="location.id") base_currency_id = serializers.IntegerField(write_only=True, source="base_currency.id") class Meta: model = Organization fields = ["id", "name", "location", "mol_number", "corporate_id", "corporate_name", "routing_code", "iban", "description", "total_of_visas", "base_currency", "logo_filename", "location_id", "base_currency_id"] def validate(self, data): content = data.get("content", None) request = self.context['request'] if not request.FILES and not content: raise serializers.ValidationError("Content or an Image must be provided") return data def create(self, validated_data): .... def update(self, instance, validated_data): .... views.py class OrganizationViewSet(viewsets.ModelViewSet): queryset = Organization.objects.all() serializer_class = OrganizationSerializer lookup_field = 'id' urls.py router = routers.DefaultRouter() router.register('organization', OrganizationViewSet, basename='organization') urlpatterns = [ path('', include(router.urls)), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I don't have idea to make post request for image field from postman?? I am stucing here long time. Any help appreciable,.. -
Django Celery: Clocked task is not running
In a Django app, I have a form that schedules an email to be sent out. It has four fields: name, email, body, send_date. I want to dynamically create a Celery task (email) to run another Celery task at the designated time. I have been able to send out the email at regular intervals (every 30 seconds) based on the form using the following code: schedule, _ = IntervalSchedule.objects.update_or_create(every=30, period=IntervalSchedule.SECONDS) @shared_task(name="schedule_interval_email") def schedule_email_interval(name, email, body, send_date): PeriodicTask.objects.update_or_create( defaults={ "interval": schedule, "task": "email_task" }, name="Send message at interval", args=json.dumps(['name', 'test@test.com', 'body']), ) However, when I have tried to schedule a task to run at a specific time (3 minutes later from the current time) via ClockedSchedule, Celery beat records the tasks and saves all the relevant settings. However, it never actually sends an email. clocked = ClockedSchedule.objects.create(clocked_time=datetime.now() + timedelta(minutes=3)) @shared_task(name="schedule_clock_email") def schedule_email_clocked(name, email, body, send_date): PeriodicTask.objects.create( clocked=clocked, name="Send message at specific date/time", task="email_task", one_off=True, args=json.dumps(['name', 'test@test.com', 'body']), ) I eventually want to dynamically set the clocked field based on the datetime the user enters into the form, so the current code is just trying to test out the way Celery works. I think I'm missing something about how this works, though. … -
Django admin/base.html page override not working
i overridde admin/base.html, changed the order of displaying applications using templatetag, everything works locally, but when I run it from docker, overriding does not work Django==2.2.16 Project structure: my_project/ |-- new_app/ |-- templates/ |-- admin/ |-- base.html settings: TEMPLATE_ROOT = os.path.join(BASE_ROOT, 'templates') TEMPLATE_DIRS = ( TEMPLATE_ROOT, ) INSTALLED_APPS = ( 'django.contrib.admin', ... 'new_app', ) docker-compose: web_app: build: . command: bash -c "python manage.py migrate --no-input && python manage.py collectstatic --no-input && gunicorn invivo.wsgi:application --bind 0.0.0.0:8000 --timeout 600 --workers 3" restart: always volumes: - .:/project - ./static:/static - ./media:/media ports: - 8000:8000 depends_on: - db env_file: - .env -
Tried to use template inheriteance but getting error all the time
I'm trying to inherit index.html and form.html from base.html. But all the time I'm undone. Please give me a solution. I'm learning Django, new in this field. Thanks in advance -
Django ORM, parent and child connecting
Django ORM G'day all, Hope everyone is well. I have two tables I'm looking to join and struggling to join in a particular way. I could easily join them with SQL but rather I would want to do it using Django. Models below; Child: class employee(models.Model): client = models.ForeignKey(client, on_delete=models.CASCADE) mySharePlan_ID = models.CharField(max_length=10, unique=True) payroll_ID = models.CharField(max_length=100) first_name = models.CharField(max_length=155,) middle_name = models.CharField(max_length=155,null=True, blank=True) last_name = models.CharField(max_length=155) TFN = models.IntegerField(null=True,blank=True) subsidary = models.CharField(max_length=155,null=True, blank=True) divison = models.CharField(max_length=155,null=True, blank=True) job_title = models.CharField(max_length=155,null=True, blank=True) tax_rate = models.FloatField(null=True,blank=True) hire_date = models.DateField(null=True,blank=True) terminiaton_date = models.DateField(null=True,blank=True) termination_reason = models.CharField(max_length=155, blank=True) rehire_date = models.DateField(null=True,blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.DO_NOTHING) class Meta: unique_together = ('client', 'payroll_ID',) def __str__(self): full_name = "Payroll ID: " + self.payroll_ID + ", " + self.first_name + " " + self.last_name return full_name Parent: class offer_eligibility(models.Model): offer = models.ForeignKey(offer,on_delete=models.CASCADE) employee = models.ForeignKey(employee,on_delete=models.CASCADE) amount_offered = models.PositiveBigIntegerField() created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.DO_NOTHING) Any employee can have many offers. I'm trying to create a view that shows a list of employees who are in a selected offer and if they have any amount_offered. This requires me to first filter the offer_eligibility by the offer, I have this queryset. … -
Django, How to call Python script outside of views.py or without reloading page
Here is basically what I have been trying to accomplish all day... use input element to pass argument to my python script run python script to pull data from another website (get request) update sql with data output data in elements on same html page I've had some success just using views.py, but I would rather not refresh the page or route to a new page. Maybe there is a way using views.py without causing that to occur? Any solution/example of how to do this would be greatly appreciated! -
Login with Google redairecting on conformation page to continue Django
I am trying to integrate Google Authentication into my login page. I am working in Django. I have added login with Google Button on my login page, but when I click on that button, I am redirecting to accounts/google/login where it's asking for conformation to continue and menu with sign-in and sign-out. But what I want is when I click on the button it should ask for accounts to login instead. This is my login screen: This is what I get on click on the button: this is my button login code in HTML: Login.html: {% if user.is_authenticated %} <p>Welcome, You are logged in as {{ user.username }}</p> {% else %} <a href="{% provider_login_url 'google' %}">Login With Google</a> {% endif %} How can I skip this conformation page , it will be glad if anyone can help me out with this thank you. -
style="width: 45px !important" in Django not works
I'm using django to make a web site. When I render<img src="{{ board.writer.profile_photo.url }}" width="45px" height="45px" style="width: 45px !important; border-radius: 50%;"/> this html, the style="width: 45px;" part changes into style="width: 100%. I have no idea why this happens. screenshot from chrome devtool I'm using python3.8, django 4.0.1 on Ubuntu 20.04. -
django custom validators function?
I have a model named X which has a STATUS_CHOICES = ( (STATUS_A, 'A'), (STATUS_B, 'B'), (STATUS_O, 'Other'), ) and the field name status = models.CharField(max_length=48, choices=STATUS_CHOICES) here i am trying to write a custom validator to for a spreadsheet when uploaded to check for the value that should return only the STATUS_CHOICES and any other value it should return error how should i write ? validators.py from app.model import X def validate_A_or_B(value): return value in dict(X.STATUS_CHOICES).values() is this correct? -
How can I use dash_bio 1.0.1 with Python and Django?
I have a website built with Python and the Django web framework. Currently, I pass the Dash applications to the html with Plotly_app but that does not work when I pass in a dashbio.igv. How can I make this functionality work? Attempting to use these examples and pass them to the front end. https://dash.plotly.com/dash-bio/igv Any help is greatly appreciated in advance, thank you. -
How to ensure fetch GET request runs after database updated?
I am having trouble ensuring that my GET request in Javascript runs after my PUT. Sometimes the JSON promise returns with updated data sometimes it does not! It appears to be random. It always displays correctly upon page reload. I am getting a "Fetch failed loading: PUT" error in my console despite the database being updated successfully. I know of await/async but was unclear if this was my solution and if so how I would implement with the correct syntax. Here is my JS: function like(id) { like_button = document.getElementById(`like-button-${id}`); if (like_button.style.backgroundColor == 'white') { fetch(`/like/${id}`, { method:'PUT', body: JSON.stringify({ like: true }) }); like_button.style.backgroundColor = 'red'; } else { fetch(`/like/${id}`, { method:'PUT', body: JSON.stringify({ like: false }) }); like_button.style.backgroundColor = 'white'; } fetch(`/like/${id}`) .then(response => response.json()) .then(post => { like_button.innerHTML = post.likes; }); } In case it is helpful here is my view in views.py: @csrf_exempt def like(request, id): post = Post.objects.get(id=id) user = User.objects.get(username=request.user.username) if request.method == "GET": return JsonResponse(post.serialize(), safe=False) if request.method == "PUT": data = json.loads(request.body) print(data.get("like")) if data.get("like"): post.Likes.add(user) else: post.Likes.remove(user) post.save() return HttpResponse(status=204) Thank you in advance for your help! -
Limiting choices on forms field DJANGO, leaving them as they were?
I have a following problem, and would appreciate some help: the question is on the bottom :) #models.py class Task(models.Model): worker_on_task = models.ForeignKey(User, related_name='task', on_delete=models.CASCADE, blank=True, default=User) #forms.py class ChageTaskStatusForm(forms.ModelForm): STATUSES = ( ('S2', 'In progress'), ('S3', 'Problem with'), ('S4', 'Finished'), ) status = forms.CharField(max_length=25, widget=forms.Select(choices=STATUSES)) class Meta: model = Task fields = ['status'] And most important: def task_details(request, pk): form = ChageTaskStatusForm(request.POST) task = get_object_or_404(Task, pk=pk) worker = get_object_or_404(User, id=request.user.id) if request.method == 'POST': if form.is_valid(): form.save() context = { 'task': task, 'form': form, } return render(request, 'usertask/task_details.html', context) I have many other fields in Task model, but I want to change only one, (status), but I get following error: IntegrityError at /4/task_details/ (1048, "Column 'worker_on_task_id' cannot be null") Request Method: POST Request URL: http://127.0.0.1:8000/4/task_details/ Django Version: 3.2.11 Exception Type: IntegrityError Exception Value: (1048, "Column 'worker_on_task_id' cannot be null") What am I missing? :/ -
I cant delete my quotes in Django? Python
Ive created a Django project where people can enter quotes by different authors. I cant figure out why Im not able to delete quotes on the same page. The user should be able to delete there own quotes <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Main</title> </head> <body> <header> <h1>Welcome, {{request.session.greeting}}</h1> <a href='/Edit_Account'>Edit My Account</a> <a href='/logout'>Logout</a> </header> {% for quote in quotes %} <p>Posted on: {{review.created_at}}</p> {% if quote.user.id == request.session.user_id %} <a href='reviews/{{quote.id}}/delete'>Delete this quote</a> {% endif %} <li>{{quote.author}} {{quote.quote}}</li> <a href="/like/{{quote.id}}">Like Quote</a> <p>{{ quote.user_likes.count }}</p> <p>(Posted by </a><a href='/users/{{quote.user.id}}'>{{quote.creator.first_name}}) </a></p> {% endfor %} {% for message in messages %} <li>{{message}}</li> {% endfor %} <h2>Add A Quote!</h2> <form action="quote/create" method="POST"> {% csrf_token %} <label for="author">Author</label> <input type="text" name="author"> <label for="quote">Quote</label> <input type="text" name="quote"> <button type="submit">Submit</button> </form> </body> </html> def delete_quote(request, review_id): quote = Quote.objects.get(id = quote_id) if quote.user.id == request.session['user_id']: quote.delete() else: messages.error(request, "This isn't yours to delete.") return redirect(f'/main') -
How can I fix the dash bio error: devtools cannot load source map dashbio@1.0.1 bundle.js.map?
I am implementing a website in Python with Django framework and using django-plotly-dash to display data. I am trying to use dash_bio's IGV feature to display some chromosome data, but when I attempt to call the functionality, I receive the following errors and the callback that returns 'dashbio.igv' is unable to execute. The errors displayed in the console: HTML code receiving the Dash app with the dashbio.igv call: line 20 is where the dash object is returned and dashbio.igv goes. {% plotly_app name=igv_app_name %} This is the python file that returns the dashbio.igv in callback: from dash import html, dcc from dash.dependencies import Input, Output import dash_bio as dashbio import pandas as pd import io import plotly.express as px from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.views.generic import DetailView from django_plotly_dash import DjangoDash from django.contrib import messages from .models import vcf_job class IgvView(DetailView): template_name = "rdr/igv.html" model = vcf_job context_object_name = "igv" def get(self, request): igv_app_name = 'igv_app' igv_app = DjangoDash(igv_app_name) HOSTED_GENOME_DICT = [ {'value': 'mm10', 'label': 'Mouse (GRCm38/mm10)'}, {'value': 'rn6', 'label': 'Rat (RGCS 6.0/rn6)'}, {'value': 'gorGor4', 'label': 'Gorilla (gorGor4.1/gorGor4)'}, {'value': 'panTro4', 'label': 'Chimp (SAC 2.1.4/panTro4)'}, {'value': 'panPan2', 'label': 'Bonobo (MPI-EVA panpan1.1/panPan2)'}, {'value': 'canFam3', 'label': 'Dog … -
Is there any way to redirect to a view from a separate view with arguments for that view function in Django?
I cannot for the life of me find a way to redirect to another view with arguments for that view in Django. I've tried the django.shortcuts redirect method, but that doesn't seem to work (it seems to want to take patterns for the url pattern and not the view function. The HttpResponseRedirect function obviously doesn't work because that function just redirects to another url. What other options are there? -
Django manual migration to add group
I am attempting to create a migration that will automatically add a group and permissions to the group when it is run. I adapted some code from the docs and an example. I can get the migration to add the group but not the permissions. I am getting the following error: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use permissions.set() instead. I am not sure how to implement this suggestion. Any ideas? The migration: from django.db import migrations, models from django.contrib.auth.models import Group, Permission from django.contrib.auth.management import create_permissions def add_group_permissions(apps, schema_editor): for app_config in apps.get_app_configs(): create_permissions(app_config, apps=apps, verbosity=0) # Employee group, created = Group.objects.get_or_create(name='Employee') if created: permissions_qs = Permission.objects.filter( codename__in=[ 'can_add_how_to_entry', 'can_change_how_to_entry', 'can_view_how_to_entry', ] ) group.permissions = permissions_qs group.save() class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.RunPython(add_group_permissions), ] -
What is the best way to package a Django project to be easily used on multiple local networks?
I have a Django project, which is to be used by multiple clients on their local networks. I don't want each of them to figure out how to setup Django with Apache or nginx, etc. Is there a way of packaging this Django project in production quality so that my clients can easily get it running on their local networks, securely?