Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, django-stores: File not found when using Google cloud storage
Ive created a file field on my model: class File(models.Model): """ Files added to the message. """ file = models.FileField(verbose_name=(_("File")), upload_to="mail/%Y/%m/%d") message = ParentalKey( "message.EventDetailMessage", on_delete=models.CASCADE, related_name="files" ) Im now trying to access the uploaded file and attach this to an email, but I cant get it to work reliably in production and locally. Right now its always working locally, but I cant seem to access the file in production (which uses django-stores with GOOGLE settings, since I use Google cloud buckets). When running the code below in production I get the message: "File was not found" for message_file in message.files.all(): logger.info(f"Attaching file {message_file}") file = message_file.file email.attach(basename(file.name), file.read(), guess_type(file.name)[0]) file.close() Can anyone point me in the right direction? -
""" Reverse for 'sample' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['sample\\-detail\\/(?P<id>[0-9]+)$']"""
I'm new in django, I got"""Reverse for 'sample' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['sample\-detail\/(?P[0-9]+)$']""" in my project and I don't know what can I fix it.please help me with codes. views.py def home(request): ctx={} ctx['sampleBotes'] = sampleBot.objects.all() return render(request,'home.html',ctx) def sample_details(request,id): ctx={} ctx['other_sample'] = otherSampleBot.objects.filter(id=id) return render(request,'sample-details.html',ctx) urls.py from django.contrib import admin from django.urls import path,include from app_base import views urlpatterns = [ path('',views.home), path('sample-detail/<int:id>',views.sample_details, name= 'sample'), ] home.html <a href="{% url 'app-base:sample' id=other_sample.id %}"><span class="more-course">other samples</span></a> -
How I can Add an extra 'status' field in auth_user Table in Django?
I want to add 'status' field in my django auth_user table, Please let me know how i can add this field. I was trying to add by signup form but i am unable to migrate from there, I am getting error. Is there are any other option where i can add this field in Django default login functionality. -
I need to convert raw MySQL query to Django ORM query
I have models.py that represent below: ` from django.db import models from django.db.models.signals import post_save # Create your models here. from django.http import request class Task(models.Model): created = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=512) cost = models.DecimalField(decimal_places=2, max_digits=8) def __str__(self): return self.description + "-" + str(self.cost) class TaskStatus(models.Model): STATUS = ( (0, 'Created'), (1, 'Taken'), (2, 'Reissued'), (3, 'On approve'), (4, 'Done'), ) task_id = models.IntegerField() created = models.DateTimeField(auto_now_add=True) status = models.PositiveSmallIntegerField(choices=STATUS, default=0) def __str__(self): return str(self.task_id) + ' ' + str(self.status) def create_status(sender, instance, **kwargs): if kwargs['created']: task_status = TaskStatus.objects.create(task_id=instance.id) post_save.connect(create_status, sender=Task) ` I have to translate that mysql query to django ORM query. I got stack on this for 2 days. And please suggest me some useful links to understand how to perform. `SELECT t.created, t.description, (SELECT MAX(s.created) FROM task_statuses s WHERE s.task_id = t.id AND s.status_type = 3 GROUP BY s.task_id) as task_on_approve FROM task t WHERE t.created BETWEEN '2019-04-01 00:00:00' AND '2019-04-30 23:59:59'; ` -
What "command" does Celery's app.control.broadcast expect?
I thought that app.control.broadcast would take an @task, but when running the following: app.send_task("workerTasks_supervisor.task_supervisor_test", args=[], queue='supervisor') app.control.broadcast("workerTasks_supervisor.task_supervisor_test", args=[], queue="supervisor") The first succeeds and the second fails with: [2019-08-01 12:10:52,260: ERROR/MainProcess] pidbox command error: KeyError('task_supervisor_test',) Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/kombu/pidbox.py", line 104, in dispatch reply = handle(method, arguments) File "/usr/local/lib/python3.5/dist-packages/kombu/pidbox.py", line 126, in handle_cast return self.handle(method, arguments) File "/usr/local/lib/python3.5/dist-packages/kombu/pidbox.py", line 120, in handle return self.handlers[method](self.state, **arguments) KeyError: 'task_supervisor_test' The worker is started with celery worker -A workerTasks_supervisor -n Supervisor --concurrency=1 --loglevel=info -Q supervisor -f /logs/celery_supervisor.log --pidfile=/logs/supervisor_pid.pid And the task itself is simple: @app.task() def task_supervisor_test(): print("working") What am I doing wrong? Thanks. -
Conditional checks not working while processing form in Django
I have a ModelForm (EditGoalForm) which I use to edit an instance of a model (Goal). Some conditions must be met before saving form data. I used if statements to check these conditions and it still saves, instead of giving an error - like the if statement does nothing. I have the following: models.py class Goal(models.Model): goal_name = models.CharField(max_length=250) goal_status = models.ForeignKey(GoalStatus, on_delete=models.CASCADE, related_name='goal_status') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='scrumy_goal_user') class GoalStatus(models.Model): status_name = models.CharField(max_length=250) forms.py class EditGoalForm(forms.ModelForm): goal_status = forms.ModelChoiceField(queryset=GoalStatus.objects.all(), empty_label="Select Goal Status") class Meta: model = Goal fields = ('goal_status',) views.py def move_goal(request, goal_id): goal_instance = Goal.objects.get(goal_id=goal_id) ERROR_MESSAGE = '''BlahBlahBlah''' has_perm_cannot_move_to_done = request.user.has_perm('application.cannot_move_to_done') has_perm_can_move_goal_anywhere = request.user.has_perm('application.can_move_goal_anywhere') has_perm_can_move_someones_goal_from_verify_to_done = request.user.has_perm('application.can_move_someones_goal_from_verify_to_done') has_perm_can_move_anybodys_goal_to_any_column = request.user.has_perm('application.can_move_anybodys_goal_to_any_column') if request.method == 'POST': form = EditGoalForm(request.POST, instance=goal_instance) if form.is_valid(): if (has_perm_cannot_move_to_done and form.cleaned_data['goal_status'] != 'Done Goal'): form.save() messages.success(request, 'Goal Update Successful') return redirect('home') else: messages.error(request, ERROR_MESSAGE) else: form = EditGoalForm(instance=goal_instance) return render(request, 'move_goal.html', {'form': form}) After if form.is_valid, I checked if the authenticated user has the permission and if the goal_status field was not set to Done Goal. If both are True, then save. However, if I set the goal_status field to Done Goal, it still saves instead of displaying an error message. What could be … -
How to deploy django app via putty with ssl certificate on aws ec2? Step-by-step
Unable to connect django app with ssl certification via putty. I've ec2 aws instance, public IP and I had already connected to the server through putty, and set postgres database and hosted django app via http protocol. I want to deploy app with ssl certificate. Kindly guide me step-by-step. Note: I only have ec2 instance, public ip, .pem key, lan ip and putty and have no access to AWS account. Error: Not permitted to connect to http://0.0.0.0:443 -
How to list in django all users profiles registered in the frontend?
This is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', enter code hereupload_to='profile_pics') This is my views.py, in my template profile.html iam trying to list in a for loop but with no sucess def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Conta criada com sucesso para! Agora é possivel efectuar o login') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form} @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Conta actualizada com sucesso!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, "title": "profile" } return render(request, 'users/profile.html', context) template is in the users app profile.html -
How to Access Context Variables Sent from Django Application in Javascript
I have sent a variable in context from my django python code as so: context = { "data": data, } return render(request, "template.html", context) but do not know how to access it in my javascript file. I have tried accessing it like this: data_from_django = {{ data }} However this simply gives me a syntax error. Please can someone tell me the correct way to access this variable. -
How can I get the keycloak ID using mozilla-django-oidc using django?
I'm using mozilla-django-oidc for my keycloak authentication with django. I can only retrieve the user email from this but can't get the other credentials like username, id etc. From keycloack config it should have in this key value pair: "claims_supported":["aud","sub","iss","auth_time","name","given_name","family_name","preferred_username","email"] but as I'm using this package I'm really confused how can I get the id means sub from it. This is my view file where i want to show the user id of the logged in user: views.py <html> <body> {% if user.is_authenticated %} <p>Current user: {{ user.email}}</p> {# shows the user email #} <p> username {{ user.sub) }}</p> {# but doesn't show the user id #} <p>Secured</p> {% else %} <a href="{% url 'oidc_authentication_init' %}">Login</a> {% endif %} </body> </html> -
Using django custom manager method as part of Q object chain
I have a custom manager with a method: # managers.py class MyModelQuerySet(models.QuerySet): ### def close_matched(self, radius=5): return self.filter( matched=True, separation__lte=radius, ) Is there anyway to use the filtering in close_matched with a set of Q object filters, for use in a view? As a simple example, something like: q = Q(another_constraint=True) | MyModel.objects.close_matched(4) but with a corrected object on the right side of the | (currently gives a TypeError since it is a queryset). If not, I'm not sure what would be best practice here to avoid duplicating the code whereywhere, is it best to rewrite the filtering logic of close_matched as a Q object that I can call in close_matched and elsewhere in views.py etc.? -
Http failure response for Django local server: 0 Unknown Error
I can see that there are several questions with this same error, I have read many of them and most are related to CORS problem. In fact, my browser is also generating CORS related warnings. I had this same problem a while ago and managed to solve by reconfiguring the header of my application. Now I'm using the same configuration, but for a different server, and I can't get over this error. I have an Ionic v4 app running in port 8100 and my Django v2.2.4 server is running in port 8000. My app header and request method (http.post using HttpClient) : const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:8000, http://localhost:8100', 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type', 'Accept': 'application/json' }) }; this.http.post("http://localhost:8000/converter2/", jsonFile, httpOptions) .pipe( finalize(() => { loader.dismiss(); }) ).subscribe(res => { if (res['success']) { this.presentToast('File uploaded complete') } else { this.presentToast('File uploaded failed') } }); I tried to configure the CORS in Django too, adding django-cors-headers with pip and configuring: # settings.py MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True but can't see changes. Browser Warnings: Cross-origin request blocked: Same Origin Policy prevents reading of remote resource at http://localhost:8000/converter2/. (Reason: 'access-control-allow-headers' symbol missing in … -
How to make CheckboxSelectMultiple checked in admin panel while editing?
I am a new Django programmer and the current version of the Django I am using is 1.11.20. I created models: Restaurants and Facilities. facilities = ( (1,'Accepts Credit Cards'), (2,'Wireless Internet'), (3,'Privat Parking'), (4,'Wheelchair Accesible'), (5,'Bike Parking'), (6,'Reservations'), (7,'Smoking Area'), (8,'Coupons'), ) class Restaurant(models.Model): restaurant_name = models.CharField(max_length=255) location = models.ForeignKey(Places, on_delete=models.CASCADE) restaurant_overview = RichTextField(blank=True) users_rating = models.DecimalField(decimal_places=1, max_digits=2) restaurant_image = models.ImageField(upload_to='restaurants') created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True) class Menu(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) menu_name = models.CharField(max_length=255) menu_items = RichTextField(blank=True) class Facilities(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) items = models.CharField(max_length=255) Created a form to turn charfield of Facilities into multi seclectable checkbox in admin panel. The code in my forms.py is as following: from .models import Facilities, facilities class FacilitiesForm(forms.ModelForm): items = forms.MultipleChoiceField(choices=facilities, widget=forms.CheckboxSelectMultiple) class Meta: model = Facilities exclude = ['created_at', 'updated'] The code in my admin panel: class MenuInline(admin.TabularInline): model = Menu max_num = 1 class FacilitiesInline(admin.TabularInline): model = Facilities form = FacilitiesForm max_num= 1 class RestaurantAdmin(admin.ModelAdmin): inlines = [ # RestaurantInline, MenuInline, FacilitiesInline, ] admin.site.register(Restaurant, RestaurantAdmin) It works fine when creating a new record. But, when I edit existing record Checkboxes set to unchecked. How can I keep the state of the checkboxes while editing the record? Do … -
How to change model attribute value from another model method
in my e commerce website , i need to make cart model active attribute value changed to False once order instance is saved so user can start a new cart after order has saved or in whatever case i determine here are my snippets: class Order(models.Model): user = models.ForeignKey(User,null=True, blank=True, on_delete=models.CASCADE) shipping_address = models.ForeignKey(Address, on_delete='CASCADE',related_name="shipping_address",null=True, blank=True) order_id = models.CharField(max_length=120, blank=True) cart = models.ForeignKey(Cart,on_delete=models.CASCADE) status = models.CharField(max_length=120, default="created", choices=ORDER_STATUS_CHOISES) shipping_total = models.DecimalField(default=5.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) active = models.BooleanField(default=True) date_posted = models.DateTimeField(default=timezone.now) # objects = OrderManager() def __str__(self): return self.order_id #self.__class__.classAttr def save(self): super(Order, self).save() if not self.cart.active ==False: self.cart.active =False self.save() class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) def checkout_home(request): cart_obj, cart_created = Cart.objects.get_or_create(user=request.user, active=True) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect("carts:home") login_form = LoginForm() address_form = AddressForm() shipping_address_id = request.session.get("shipping_address_id", None) address_qs = None if request.user.is_authenticated: address_qs = Address.objects.filter(user=request.user) order_obj, order_obj_created = Order.objects.get_or_create(active=True,user=request.user, status='Created',cart=cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] order_obj.save() context = { "object": order_obj, "login_form": login_form, "address_form": address_form, "address_qs": address_qs,} return render(request, "carts/checkout.html", context) this … -
Django: Retrieving the private key of selected dropdown option in Ajax call
I have two models like this: class ScenarioMarket(models.Model): title = models.CharField(max_length=50, default="") description = models.TextField(default="") b = models.IntegerField(default=100) cost_function = models.IntegerField(default=0) open = models.BooleanField(default=True) def __str__(self): return self.title[:50] def get_absolute_url(self): return reverse('market_detail', args=[str(self.id)]) class Scenario(models.Model): description = models.TextField(default="") current_price = models.DecimalField(max_digits=5, decimal_places=2, default=0.00) share = models.IntegerField(default=0) market = models.ForeignKey( ScenarioMarket, on_delete=models.CASCADE, related_name='scenarios', default=None) def __str__(self): return str(self.description) In my template, I have a dropdown menu that loops over (the descriptions of) all the scenarios available on the scenario market in question, with each option taking the pk of the relevant scenario as its value: <form action="" method="GET" id="scenario-dropdown"> {% csrf_token %} <select> {% for description in scenariomarket.scenarios.all %} <option value="{{ scenario.id }}"> {{ description }} </option> {% endfor %} </select> </form> What I then want to do is pick up the pk of the selected option in the dropdown menu in an Ajax call. I thought I would be able to it this way: var scenario_id = document.getElementById("scenario-dropwdown").value But looking in the console, I get Uncaught TypeError: Cannot read property 'value' of null, so clearly it's not working - likely with respect to the <form>. What am I doing wrong? -
Django: Save objects with circular references
I'm using Django with the PostgreSQL backend. Now, I've two models with circular references: Thread exists of a startpost of type Post Post exists of a thread of type Thread My problem is that I cannot create any of the two objects because they are dependent on each other. One solution to that problem is the DEFERRABLE INITIALLY DEFERRED constraint that is also supported by PostgreSQL. After some research I found the following post: https://www.reddit.com/r/django/comments/72qwr6/why_does_the_postgresql_backend_make_foreignkeys/ So it looks like that Django also supports this and, as long as you create your objects in a transaction, it should work. However, when I test it I get an IntegrityError, it looks like my Django did not create the DEFERRABLE INITIALLY DEFERRED constraint. I'm confused. Can someone clarify the situation? Did I miss something? -
TemplateDoesNotExist Django Version: 2.2.3
I'am learning django and building a page,I get the TemplateDoesNotExist error, I don't know how to fix this.But I don't know show what part's of the code. TemplateDoesNotExist at / Leaning_logs/base.html Request Method: GET Request URL: http://localhost:8000/ Django Version: 2.2.3 Exception Type: TemplateDoesNotExist Exception Value: Leaning_logs/base.html Exception Location: D:\learning-note\ll_env\lib\site-packages\django\template\backends\django.py in reraise, line 84 Python Executable: D:\learning-note\ll_env\Scripts\python.exe Python Version: 3.7.3 Python Path: ['D:\learning-note', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37', 'D:\learning-note\ll_env', 'D:\learning-note\ll_env\lib\site-packages'] Server time: Thu, 1 Aug 2019 10:45:39 +0000 -
How to get the related model class name from a ManyToOneRel object?
I have a class structure like the following: class Parent(models.Model): some_fields = ... def get_related_child_file_models_info(self): """ This return a generator containing all the related file model info for each child """ links = ( [f.name, f] for f in self._meta.get_fields() if (f.one_to_many or f.one_to_one) and f.auto_created and not f.concrete and "files" in f.name ) return links class ChildFileA(models.Model): ... parent = models.ForeignKey( on_delete=models.CASCADE, related_name="child_a_files" ) file = models.FileField() ... class ChildFileB(models.Model): ... parent = models.ForeignKey( on_delete=models.CASCADE, related_name="child_b_files" ) file = models.FileField() ... If I use this generator inside a for loops I get ['child_a_files', <ManyToOneRel: app_name.childfilea>] and ['child_b_files', <ManyToOneRel: app_name.childfileb>] The goal is to handle a complex files upload process where I have around 30 different models to store some files for each parents. And I try to avoid having to manually create the code for each. How to get the class name ChildFileA and ChildFileB from the ManyToOneRel object? -
Django Management Command : 'Command' object has no attribute 'META'
I have a Management command, that prints out a function output. But after execution it gives an error. What is the error and how to resolve it? (VE) C:\Users\Bitswits 3\Desktop\LCRProject\LeastCostRouting>python manage.py my_dest_commands {'48': ['Tata', ' 0.531', 'Tata', ' 0.531', 'Tata', ' 0.531', 'Tata', ' 0.531', 'Tata', ' 0.531', 'Tata', ' 0.531'], '23': ['Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888'], '96': ['Tata', ' 1.260', 'Tata', ' 1.260', 'Tata', ' 0.205', 'Tata', ' 0.205', 'Tata', ' 0.030', 'Tata', ' 0.030', 'Tata', ' 0.305', 'Tata', ' 0.305', 'Tata', ' 1.260', 'Tata', ' 1.260', 'Tata', ' 0.205', 'Tata', ' 0.205', 'Tata', ' 0.030', 'Tata', ' 0.030', 'Tata', ' 0.305', 'Tata', ' 0.305', 'Tata', ' 1.260', 'Tata', ' 1.260', 'Tata', ' 0.205', 'Tata', ' 0.205', 'Tata', ' 0.030', 'Tata', ' 0.030', 'Tata', ' 0.305', 'Tata', ' 0.305', 'PTCL', ' 0.150', 'PTCL', ' 0.150', 'PTCL', ' 0.005', 'PTCL', ' 0.005', 'PTCL', ' 0.305', 'PTCL', ' 0.305', 'PTCL', ' 0.150', 'PTCL', ' 0.150', 'PTCL', ' 0.005', 'PTCL', ' 0.005', 'PTCL', ' 0.305', 'PTCL', ' 0.305', 'PTCL', ' 0.150', … -
How to assign the object or model to the child model which is Generic Foriegn key
i have a model which i made it as a generic foriegn key and i want to apply the related parent model to it in the views while posting the form my models: class ContactDetails(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,blank=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey('content_type', 'object_id') address = models.TextField() telephone = models.CharField(max_length=15, blank=True) mobile = models.CharField(max_length=15, blank=True) email = models.EmailField(blank=True) class Supplier(models.Model): name = models.CharField(max_length=100) mobile = models.CharField("Primary Mobile", max_length=15, unique=True) email = models.EmailField() my views.py def supplier_registration(request): details_formset = generic_inlineformset_factory(ContactDetails, form=ContactDetailsForm, ct_field='content_type', fk_field='object_id',extra=1) if request.method=="POST": form = SupplierForm(request.POST) formset = details_formset(request.POST) if form.is_valid() and formset.is_valid(): f = form.save() fs = formset.save(commit =False) for i in fs: i.content_type = Supplier i.object_id = f.id i.save() return redirect('/suppliers/') else: form = SupplierForm() formset = details_formset() return render(request , 'single_form.html',{'form':form,'formset':formset}) i am getting error : 'NoneType' object has no attribute '_meta' -
AWS S3: image is uploading to bucket but file is not showing in heroku Django
Image is uploading to bucket, but it is not showing in the app when it runs. Please help here Iam using Employee.objects.all() function to fetch the details from database. Please have a look on it and please help me site adress is : https://mttemployee.herokuapp.com you can test it using, user name: first and emp Id: 1 please help me fast settings.py file import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') SECRET_KEY = '=^tpe+kln3xg-_kclfay62+4l6c@_l%fj_^k@h0xc5%(0cp^h9' DEBUG = True ALLOWED_HOSTS = ['mttemployee.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'manager', 'storages' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'empmanagement.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'empmanagement.wsgi.application' # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'empmanage', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'USER': 'postgres', 'PASSWORD': '1234', 'HOST': 'localhost', } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ … -
Dockerfile configuration for apache serving django project
Currently i'm trying to deploy my django app via docker. I just started to learn the hole thing, so now I want to build an image based on httpd official image that creates new blank django project (just to try) and serves it by apache. (I am using ubuntu 18) My Dockerfile: FROM httpd RUN apt-get update && apt-get upgrade -y RUN apt-get remove --purge apache2 apache2-utils \ && apt-get install -y --reinstall apache2 apache2-utils RUN apt-get install -y libapache2-mod-wsgi-py3 RUN apt-get install -y python3 python3-pip python3-venv RUN mkdir /home/django_project ENV VIRTUAL_ENV=/home/django_project/venv RUN python3 -m venv $VIRTUAL_ENV ENV PATH="$VIRTUAL_ENV/bin:$PATH" WORKDIR /home/django_project RUN . venv/bin/activate \ && pip install django==2.1 \ && django-admin startproject new \ && chown :www-data new/ RUN . venv/bin/activate && python new/manage.py migrate RUN chown :www-data new/db.sqlite3 && chmod 664 new/db.sqlite3 COPY django-site.conf /etc/apache2/sites-available/django-site.conf RUN a2ensite django-site.conf && a2dissite 000-default.conf && a2dissite default-ssl.conf EXPOSE 80 And django-site.conf (apache configuration for new site): <VirtualHost *:80> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static "/home/django_project/new/static" Alias /media "/home/django_project/new/media" <Directory "/home/django_project/new/static"> Require all granted </Directory> <Directory "/home/django_project/new/media"> Require all granted </Directory> <Directory "/home/django_project/new/new"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / "/home/django_project/new/new/wsgi.py" WSGIDaemonProcess example.com python-path="/home/django_project/new" python-home="/home/django_project/venv" WSGIProcessGroup example.com </VirtualHost> after … -
Django set ManytoManyField to default user model
I need to set a manytomany relation to default django user table.Is there any way to implement it rather than using AbstractUser method of django (extending User Model)? -
Unable to Pass SQL Object From Python to Javascript in Django
I am trying to send a single SQL object to my Javascript in Django using json.dumps however I get the error: Object of type List is not JSON serializable when I run the following code: user_data = List.objects.get(user=request.user.username) context['list'] = json.dumps(user_data) return render(request, "template.html", context) The SQL Object has three fields, the first is a username and the other two are lists. Please can you tell me how to convert this to JSON correctly. -
Display group name of user with a template
For the staff members of my website, I am displaying a list of all users registered and I want to display their group. It's working except that I get <QuerySet [<Group: UserGroup>]> instead of UserGroup. Tried to use group = form.cleaned_data['group_name'] but I get this error: invalid literal for int() with base 10: 'Viewers' at user.groups.add(group). forms.py: class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) is_active = forms.BooleanField(initial=True, required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'group_name', 'is_active', ) views.py: @login_required @group_required('Staff') def registerView(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = RegisterForm() return render(request, 'accounts/register.html', {'form': form}) # Display all active users in a table class UserView(LoginRequiredMixin, GroupRequiredMixin, ListView): template_name = 'accounts/display_users.html' group_required = ['Staff'] queryset = User.objects.filter(is_active=True) display_users.html: {% block main %} <table class="table"> <thead class="thead-dark"> <p> <tr> <th scope="col"># id</th> <th scope="col">Username</th> <th scope="col">Group</th> <th scope="col">Email address</th> <th scope="col">First name</th> <th scope="col">Last name</th> </tr> </thead> {%for instance in object_list%} <tbody> <tr> <td>{{instance.id}}</td> <td><a href = "{% url 'accounts:update' instance.id %}">{{instance}}</a></td> <td>{{instance.groups.all}}</td> <td>{{instance.email}} …