Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems with changing the value of useState when running components repeatedly through the response map
I want to repeat the components through the map and display the information that received the aixos on each tag, but when I checked, only the last value of the repetition is being posted. When I printed it out as console, the value of searchHospitalAdd, searchHospitalName didn't change immediately, and it seems that only the last value is included Why is it like this? Am I using it wrong? Or is the problem with the time to reply after sending the post request? I don't think this is right, but I don't know I mean the SetPendPatientView tag! We're developing React and Django drf I want you to give me a solution const Hospitals = () => { const state = useLocation().state; const [hospitals, setHospitals] = useState([]); const [ScrollActive, setScrollActive] = useState(false); const [hospitalInfoModalOn, setHospitalInfoModalOn] = useState(false); const [hospitalInfo, setHospitalInfo] = useState([]); const [wait_count, setWait_count] = useState(''); const [searchHospitalAdd, setSearchHospitalAdd] = useState(''); const [searchHospitalName, setSearchHospitalName] = useState(''); useEffect(() => { axios .post('http://localhost:8000/patient/hospital_srch/', { hospitalDep: state.hospital_dep }) .then(function (response) { const hospital = JSON.parse(response.data); setHospitals(hospital); console.log(state.hospital_dep); console.log(hospital); }) .catch(function (error) { alert(error); }); return () => {}; }, [state]); useEffect(() => { axios .post( 'http://localhost:8000/reservation/wait_search/', { hospital_address: searchHospitalAdd, hospital_name: searchHospitalName }, … -
Django migrations are faked after reverse
I am working on different tasks in the project, so i have to switch between git branches and do reverse migrations. But after reversing the migrations, when re-building the project on the same branch, these migrations are launched as faked and are not applied. I have to remove them from the django migrations table and run them again with the migrate command. Please tell me what is this effect and if it can be somehow avoided. Didn't find any information about this. I reverse migrations with the command django-admin migrate <app_name> <number_migration> -
How to add multiple models to a single listview?
i need to be able to display information from multiple models in a single listview but haven't a clue how to go about doing this any help would be very helpful... here is my code for me views.py: from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView from . models import Post, Task from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator @method_decorator(login_required, name='dispatch') class HomeView(ListView): template_name = 'home.html' model = Post @method_decorator(login_required, name='dispatch') class Task(ListView): model = Task template_name = 'tasks.html' here is my code for me models.py: from django.db import models from django.contrib.auth.models import User class Post(models.Model): type = models.CharField(max_length=255) title = models.CharField(max_length=255) link = models.CharField(max_length=255) auther = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() def __str__(self): return self.title + ' | ' + str(self.auther) class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) urgency = models.CharField(max_length=255) title = models.CharField(max_length=255) description = models.TextField() def __str__(self,): return str(self.user.username) + ' | ' + 'Tasks' here is my html: {% for task in object_list %} <a href="#" class="list-group-item list-group-item-action bg-transparent border border-secondary"> <h class="mb-1">{{task.title}}</h> <p class="mb-1">{{task.description}}</p> <a class="mb-1">{{task.urgency}}</a> </a> {% endfor %} {% for post in object_list %} <span> <div class="card text-secondary-emphasis border border-secondary mb-4" style="background-color: #0d1117;"> <div class="card-header border border-secondary">{{post.type}}</div> <div class="card-body"> <h5 class="card-title"style="color: … -
Is there any python specific solution for conversion of an excel file to its respective pdf?
I have been trying to convert an excel file to its pdf form. But the django server is getting hanged. I read about this issue with flask server also https://forum.aspose.com/t/python-flask-web-server-hang-at-aspose-cells/232218/6 As of now have used aspose-cells python library which has dependency upon Java. It works fine inside console but not with Django web server (as the server is getting hanged indefinitely) import asposecells import jpype jpype.startJVM() from asposecells.api import Workbook workbook = Workbook("input.xlsx") workbook.save("output.pdf") jpype.shutdownJVM() I am trying it out on mac M2. -
django filter is not working Plz solve this as soon as posible
i have two same code in Django views.py file shown in pis This is code in my Views.py file and this is Output of my code but Queryset is not working enter image description here plz help me to solve this solve plz, i had try many time on this code -
Filtering queryset for a formset doesn't work
I'm trying to display a formset with a ChoiceField and I want to filter this ChoiceField queryset. But it just doesn't work. So I've tried this def create_formation_template(request, pk): formation = Formation.objects.get(id=pk) def_formation_template = inlineformset_factory(Formation, FormationTemplate, fields=('position',), extra=formation.defender_number) defenders_queryset = FormationTemplate.objects.filter(position__type='Defender') def_formset = def_formation_template(queryset=defenders_queryset, instance=formation) return render(request, 'formation_template_form.html', {'def_formset': def_formset} When I display the formset on a template, there are no errors but it does not filter the ChoiceField queryset at all -
unique_together not working as expected in view
I added unique_together in the Django model. It works fine in the Django admin panel but doesn't work when I create model instances in a for loop in the Django view. My Model: class Parent(models.Model): attribute_1 = models.CharField(max_length=100) attribute_2 = models.IntegerField() attribute_3 = models.CharField(max_length=100) class Meta: unique_together = (("attribute_1", "attribute_2"),) View: class ParentView(View): template_name = "app/index.html" def get(self, *args, **kwargs): for i in range(10): Parent.objects.create( attribute_1=f"value-{i}", attribute_2=i, attribute_3=f"value-{i}", ) return render(self.request, self.template_name) Problem: When I open this view, it creates the entries in the Parent model. when I refresh the page, I expect a unique value error but it doesn't give any error at all and creates entries again. No matter how much time I reload the page, it creates duplicate entries without giving an error. What I tried? I tried to change my DB from sqlite3 to PostgreSQL but it didn't work. I tried to switch attributes but no luck. It works perfectly fine on the admin panel. -
How to convert text file (raw data) data into excel in pandas or python?
** How to conver text file data into excel arrange into header and values in excel ? **text.file data [GDIP] Host address - 200.00.99.22 Host address (decimal) - 122345560 Host address (hex) - B00009 Net address - 19.0.0.8 Networker - 2.2.2.2.2 Host address - 500.00.00.00 Host address (decimal) - 987654 Host address (hex) - D00008 Net address - 197.0.0.99.00 Networker - 3.3.3.3.3 Output Excel data Host address Host address (decimal) Host address (hex) Net address Networker 200.00.99.22 122345560 B00009 19.0.0.8 2.2.2.2.2 500.00.00.00 987654 D00008 197.0.0.99.00 3.3.3.3.3 -
Django's Generic UpdateView: How to pass value to the hidden form field?
I am trying to combine Django's generic UpdateView and hidden input field. My purpose is to track whether a post was edited after it was created or not. Hidden field name is "updated". views.py: class PostUpdateView(UpdateView): model = Post template_name = 'journal/post_update_form.html' form_class = PostUpdateForm success_url = reverse_lazy('my_posts') models.py: class Post(models.Model): title = models.CharField(max_length=500) text = models.TextField(max_length=2000, null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) #storing the link to media files in CharField image = models.CharField(max_length=500, null=True, blank=True) audio = models.CharField(max_length=500, null=True, blank=True) video = models.CharField(max_length=500, null=True, blank=True) rubric = models.CharField(max_length=100, default="No rubric", choices=RUBRIC_CHOICES) private = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) updated = models.CharField(max_length=10, default="False") forms.py: from django import forms from .models import Post class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = ["title", "text", "image", "audio", "video", "rubric", "private", "updated"] widgets = {'updated': forms.HiddenInput(attrs={'value':"updated"})} relevant part of update form template: <form action="" method="POST"> {% csrf_token %} {% for field in form %} {% if field != form.rubric and field != form.private %} <div class="mb-3 form-group"> <label for="{{field.name}}" class="form-label">{{field.label}}</label> {{field.errors}} {% if field == form.text %} <textarea type="text" class="form-control" id="{{field.name}}" name="{{field.name}}">{{field.value|default_if_none:"" }}</textarea> {% elif field == form.updated %} <input type="hidden" id="{{field.name}}" name="{{field.name}}" value="updated"> {% else %} <input type="text" … -
How to authenticate user in Django
I am trying to log in a user in Django and redirect them back to the homepage with an if statement in the navbar that will display logout if the user is logged in or authenticated and register and login links if they're not authenticated. However, when I click login it goes back to the homepage but none of the expected changes are visible, if you see my views.py file the view is supposed to print a message depending on the action taken but these messages are only displayed on the Django admin page. What am I not doing? This is the login form: <form action="" method="POST"> {% csrf_token %} <!-- Email input --> <div class="form-outline mb-4"> <input type="email" id="user-email" class="form-control" name="login-email" placeholder="Enter email"/> <label class="form-label" for="user-email">Email address</label> </div> <!-- Password input --> <div class="form-outline mb-4"> <input type="password" id="user-password" class="form-control" name="login-password" placeholder="Enter password"/> <label class="form-label" for="form2Example2">Password</label> </div> <!-- 2 column grid layout for inline styling --> <div class="row mb-4"> <div class="col d-flex justify-content-center"> <!-- Checkbox --> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="form2Example31" checked /> <label class="form-check-label" for="form2Example31"> Remember me </label> </div> </div> <div class="col"> <!-- Simple link --> <a href="#!">Forgot password?</a> </div> </div> <!-- Submit button --> <button type="submit" … -
django-admin startproject webproject . The system cannot find the file specified
When I tried following the instructions to create my Django project with these steps: Create the Django project In the VS Code Terminal where your virtual environment is activated, run the following command: django-admin startproject web_project . It didn't work. Ran in (venv): django-admin startproject webproject . Got: The system cannot find the file specified -
Django celery beat does seems to get triggered when on my EC2 instance
so this task runs completely fine when locally : @shared_task def test(): print('test') app.conf.beat_schedule = { 'my-task-every-1-minutes': { 'task': 'statistic_status.tasks.test', 'schedule': crontab(minute='*/1'), }, } when on my EC2 and i start the worker it shows my tasks correctly but when starting the beat the server looks like running fine but it does no get triggered. Locally everything works fine and on EC2 the only way I could triggered my tasks is from the python shell. Any help here ?? -
Django generate thumbnail with MoviePy, problem with Path
How to get the absolute path to a video, that works in development (Windows) and production (Ubuntu), ive tried almost anything, here is the closest i got to getting it right, I am trying to generate a thumbnail for a video when its posted ` from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent def generate_thumbnail(instance): filename = Path.joinpath(BASE_DIR, 'media/video_files') print(filename) thumbnail = VideoFileClip(str(filename)+instance.video.url) name = instance.video.url + '.png' time = random.randrange(60) thumbnail.save_frame('media/uploads/thumbnail' + name, t=time, withmask=True) instance.thumbnail = name ` It never gives me a good path, its ether with '/' or with ''. MoviePy error: the file C:\Users\User 1\Desktop\django\lumen\media\video_files/media/uploads/video_files/22/29/Elvis_-_If_I_Can_Dream_Official_Live_Performance_fcw0WKp.mp4 could not be found! Please check that you entered the correct path. -
Django product count per category
Have below models class TreatmentCategory(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name class Treatment(models.Model): unique_id = models.UUIDField('Unique Record ID', default=uuid.uuid4, editable=False) name = models.CharField('Treatment Name', max_length=255, db_index=True, unique=True) category = models.ForeignKey(TreatmentCategory, on_delete=models.PROTECT) duration = models.PositiveSmallIntegerField('Treatment Duration (min)') price = models.DecimalField('Treatment Cost', max_digits=9, decimal_places=2) description = models.TextField(null=True, blank=True) active = models.BooleanField(default=True) def __str__(self): return self.name class Therapist(models.Model): day_options = [ ("Off Day", "Off Day"), ("On Leave", "On Leave"), ("On Duty", "On Duty"), ] unique_id = models.UUIDField('Unique Record ID', default=uuid.uuid4, editable=False) name = models.CharField('Therapist Name', max_length=255) contact = models.CharField('Phone Number', max_length=12, blank=True, null=True) day_status = models.CharField( 'Duty Status', max_length=255, choices=day_options, default='On Duty' ) status = models.BooleanField( 'Status of Therapist', default=True, ) treatments = models.ManyToManyField(Treatment, related_name='therapists') def __str__(self): return self.name Would like to output all therapists and a total count of treatments per category they have records i.e each therapist may have different treatments per category thus they wont have same number of treatments therapist1 | treatmentcategory1 (number of treatments) | treatmentcategory2 (number of treatments) | treatmentcategory3 (number of treatments) therapist2 | treatmentcategory1 (number of treatments) My current code as below, its displaying therapists however, instead of treatmentcategories, it showing treatments category = (TreatmentCategory.objects.filter(treatment__active=True) .prefetch_related('treatment_set') .annotate(treatment_count=Count('treatment__name')) ) queryset = (Therapist.objects.filter(status=True) .prefetch_related( Prefetch('mytreatments', … -
Django does not find the Urls.py in the app
these are my settings, where I've always worked. I've been working with Django for 3 months but I haven't had anything like that until now. my thoughts are by '' at the beginning of the urlspattern to make the home template the main template from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('inventory.urls')), # code urls.py in the app from . import views from django.urls import path urlpatterns = [ path('', views.home, name='home'), path('base/', views.BaseTemplateView.as_view(), name='base'), # Menu Item URLs path('menu/', views.MenuItemListView.as_view(), name='menu_item_list'), path('menu/<int:pk>/', views.MenuItemDetailView.as_view(), name='menu_item_detail'), #the View def home(request): return render(request, 'home.html') class BaseTemplateView(TemplateView): template_name = 'base.html' class MenuItemListView(ListView): model = MenuItem template_name = 'menu_item_list.html' context_object_name = 'menu_items' class MenuItemDetailView(DetailView): model = MenuItem template_name = 'menu_item_detail.html' # the setting for the template folder OOT_URLCONF = 'djangodelights.urls' TEMPLATE_DIR = os.path.join(BASE_DIR,"templates") 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', ], # Installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'inventory.apps.InventoryConfig', **I was expecting ,when a start the server e get the home.html template.no matter which path I enter manually, I always get the same message ** *Using the URLconf defined in … -
pass the value from form with autocomplete jquery to view in django
I made a form to send data to a view. The form input has a jquery autocomplete. <form method="get" action=""{% url 'ville_detail' %}""> <label for="villeselect">Product</label> <input type="text" name="id" id="villeselect"> <button type="submit">Go</button> </form> </div> <script> $(function () { $("#villeselect").autocomplete({ source: '{% url 'autorecherche' %}', minLength: 3 }); }); </script> the method in views.py "autorecherche" manages this form and the autocomplete def autorecherche(request): if 'term' in request.GET: qs = VilleFrance.objects.filter(name__istartswith=request.GET.get('term')) cible = list() for product in qs: cible.append(product.name) return JsonResponse(cible, safe=False) return render(request, 'ville/ville_recherche.html') how to pass the submit valueto this view. I tried but I can't find the solution class TestDetailView(DetailView): template_name = 'ville/ville_detail.html' model = Article def get_context_data(self, **kwargs): context = super(TestDetailView, self).get_context_data(**kwargs) my_id = self.kwargs['pk'] item = Article.objects.values_list(('nomVille'),flat=True).get(pk=my_id) context['item'] = item return context the url looks like this path('ville/<int:pk>/city_detail', VilleDetail.as_view(), name='ville_detail'), thank for any help. -
when i clicked on add to cart button it first check "is user login??" then execute jquery
when i clicked on Add to cart button , it first chek that user login or not if login then continue otherwise redirect to login page $('.divpr').on('click', 'button.cart' ,function () { var idstr = this.id.toString(); if (cart[idstr] != undefined) { console.log("exist"); cart[idstr][0] = cart[idstr][0] + 1; cart[idstr][4]=cart[idstr][4]+cart[idstr][3] localStorage.setItem('cart', JSON.stringify(cart)); } else { qty = 1; price = document.getElementById('price' + idstr).innerHTML; totalPrice=document.getElementById('price' + idstr).innerHTML; image = document.getElementById('img' + idstr).src; aname = document.getElementById('name' + idstr).innerHTML; console.log("not"); cart[idstr] = [qty, aname, image, parseInt(price),parseInt(totalPrice)]; } localStorage.setItem('cart', JSON.stringify(cart)); console.log(cart) }); it add item to cart even i am not login i want it redirect when i am not loggedin -
How do I register a custom user type in Django 4.1?
So, I am a beginner and I'm coding a django application that has a 3 user types in total but to make the code readable and understandable I'm just gonna assume we have 2 user types. One is a doctor and one is a patient. I've created this custom user so far: in models.py class User(AbstractUser): is_doc = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) objects = UserManager() manager.py class UserManager(BaseUserManager): def create_user(self, email, password=None): if email is None: raise TypeError('Users must have an email address.') user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_patient(self, email, password): if password is None: raise TypeError('Must have a password') user = self.model(email=self.normalize_email(email)) user.set_password(password) user.is_patient = True user.save() def create_superuser(self, email, password): if password is None: raise TypeError('Superusers must have a password.') user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user Patient Model is as follows: class Patient(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=70) last_name = models.CharField(max_length=70) address = models.CharField(max_length=210) phone = models.CharField(max_length=15) email = models.EmailField(max_length=110) password = models.CharField(max_length=65) def __str__(self): return self.first_name + " " + self.last_name I have separate signups for patient and doctor and don't want a user type field in my form so I have all the detail … -
Vue.js/JavaScript Errors When Running Vue/Django App on OpenShift but not Locally
I have a vue django app that runs and works fine locally. It does not work once I deploy it to my OpenShift pod, however. These are the specific errors I get when I navigate to the pod URL: Uncaught ReferenceError: jQuery is not defined at select2.min.js:2:241 at select2.min.js:2:249 vue.js:9330 You are running Vue in development mode. Make sure to turn on production mode when deploying for production. See more tips at https://vuejs.org/guide/deployment.html vue.js:5108 [Vue warn]: Property or method "titleInvalid" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties. (found in <Root>) warn$2 @ vue.js:5108 vue.js:5108 [Vue warn]: Error in render: "TypeError: titleInvalid is not a function" (found in <Root>) warn$2 @ vue.js:5108 vue.js:3732 TypeError: titleInvalid is not a function at Proxy.eval (eval at createFunction (vue.js:11632:18), <anonymous>:3:883) at Vue._render (vue.js:2509:30) at Vue.updateComponent (vue.js:2948:29) at Watcher.get (vue.js:4178:35) at new Watcher (vue.js:4168:53) at mountComponent (vue.js:2965:7) at Vue.$mount (vue.js:9311:14) at Vue.$mount (vue.js:11870:20) at Vue._init (vue.js:4724:18) Are there any specific settings I need to check for in my django project settings or in my OpenShift pod (or project) settings? I wasn't … -
How to properly contenarize a django-react multicontainer app using docker for production and deployment ? (Nginx, Gunicorn)
I built a small blog to learn to use docker and docker-compose. I am new to programming and web development. I built the frontend with react and next. the backend with django and a postgresql database. I managed to setup a development environment with bind mounts, volumes, Dockerfiles and docker-compose.yml that worked fine and i learned a lot. here was my base docker-compose.yml file: 1 version: "3.8" 1 2 services: 3 db: 4 image: postgres:12.0-alpine 5 restart: unless-stopped 6 volumes: 7 - postgres_data:/var/lib/postgresql/data/ 8 env_file: 9 - ./api/.env.dev 10 11 blog-dev: 12 image: "blog:dev" 13 build: 14 target: development_build 15 context: ./api 16 cache_from: 17 - "blog:dev" 18 args: 19 DJANGO_ENV: development 20 command: python -Wd myblog/manage.py runserver 0.0.0.0:8000 21 ports: 22 - 8000:8000 23 env_file: 24 - ./api/.env.dev 25 depends_on: 26 - db 27 28 front-dev: 29 image: "front:dev" 30 build: 31 target: development_front 32 context: ./frontend 33 command: npm -Wd start 34 ports: 35 - 3000:3000 36 volumes: 37 - ./frontend:/front 38 - /front/node_modules 39 40 volumes: 41 postgres_data: now i want to deploy it on AWS with ECR and elastic beanstalk. I read quite a bit about Dockerrun.aws.json files and config files, etc. to that end, my … -
Django_filters - ModelChoiceFilter - How to filter based on the page_ID the user is visiting
I would like the user to be able to filter based on categories. I am using django_filters. Two important things: These categories are not hard coded in the model, but provided by the a user type ( in my case a Venue, not an actual user therefore request.user does not work. Or at least I dont know how to use it in my situation). I only want to show the categories relevant to the Venue ID page. I am probably lacking a bit of "vocabulary" to express this in a way django understand. It's a recurring problem I have, and somehow always manage to go around it. I think this time I am definitely going to need to do something about it. Would be useful to find out! model class Catalogue(models.Model): product = models.ManyToManyField('Product', blank=True) type = models.TextField('type', blank=True, null=True) url path('show_venue/<venue_id>', views.show_venue,name="show-venue"), views def show_venue(request, venue_id): if request.method == "POST" and 'btnreview_form' in request.POST: form = CatalogueReviewForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.product_id = venue_id # links to product ID in Catalogue Model and return product name data.venue_id = request.POST.get('venue_id') # prints venue ID in form data.user_id = request.user.id data.save() ven_id = request.POST.get('venue_id') print(data) form.save() return HttpResponseRedirect(ven_id) else: venue … -
Render a blank response (Django Template Language)
i want print the name of a given post list but it render an blank response.. Below is the code of views.py from django.shortcuts import render post = [ { 'name':'Abc, 'dob':'01/01/1998' }, { 'name':'Xyz', 'dob':'24/01/1993' } ] def home(requests): return render(requests,'app1/home.html',dict(post)) Content of home.html {% for item in post %} <p>name is {{ item.name }}</p> {% endfor %} here it display the blank response instead of printing the name..So how can i fix this issue ? What i tried is created another variable and pass it to the home.html views.py def home(requests): context = { 'posts':post } return render(requests,'app1/home.html',context) home.html {% for item in posts %} <p>name is {{ item.name }}</p> {% endfor %} Above code gives the expected result.. -
Error with Wagtail URLs for media files: subclasses of Storage must provide a url() method
I am using Wagtail in a project and have a problem with both wagtailimages.Image and wagtaildocs.Document fields. When using DRF to access the URL data I get a "subclasses of Storage must provide a url() method" error. My configuration is that I have to use Bunny.net for storing media files. In order to do that, I use a library called django-bunny-storage (https://pypi.org/project/django-bunny-storage/) that works well with non Wagtail projects. This is my simplified model in which I removed all other fields: class Content(models.Model): illustration = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) uuid = models.CharField(max_length=255, primary_key=True, default=uuid.uuid4, editable=False) document = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) panels = [ ImageChooserPanel('illustration'), DocumentChooserPanel('document'), ] As per django-bunny-storage I also had to modify the template context_processors array TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'django.template.context_processors.media' ], }, }, ] I created a small modelserializer for Content that always returns this same error when I try to access the url of the Document or the Image field. from wagtail.images.models import Image, AbstractImage, AbstractRendition from wagtail.documents.models import Document class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = (('file'),) class DocumentSerializer(serializers.ModelSerializer): class Meta: model … -
django unittest error when have two test method in one class
I have question table in my model and each question can have some options : Models.py : class Question(BaseModel): class DifficultyLevel(models.IntegerChoices): EASY = 1 MEDIUM = 2 HARD = 3 question_text = models.TextField() level = models.IntegerField(default=1, choices=DifficultyLevel.choices) def __str__(self): return truncatewords(self.question_text, 7) class Option(BaseModel): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='options') title = models.CharField(max_length=255) is_correct = models.BooleanField(default=False) def __str__(self): return self.title for updating questions I have : Views.py : class QuestionByIDAPIView(BadRequestSerializerMixin, APIView): def patch(self, request, question_id, company_code): serializer = InputQuestionSerializer(question_obj, data=request.data, partial=True) if not serializer.is_valid(): return self.serializer_error_response(serializer) serializer.save() return success_response(serializer.data, status_code=status.HTTP_200_OK) serializers.py : def update(self, instance, validated_data): options = validated_data.pop('options', None) instance.question_text = validated_data.get('question_text', instance.question_text) instance.level = validated_data.get('level', instance.level) instance.save() options_with_same_question_instance = Option.objects.filter(question=instance.pk).values_list('id', flat=True) options_id_pool = [] if options: for option in options: if "id" in option.keys(): if Option.objects.filter(id=option['id']).exists(): option_instance = Option.objects.get(id=option['id']) option_instance.title = option.get('title', option_instance.title) option_instance.is_correct = option.get('is_correct', option_instance.is_correct) option_instance.save() options_id_pool.append(option_instance.id) else: continue else: options_instance = Option.objects.create(question=instance, **option) options_id_pool.append(options_instance.id) for option_id in options_with_same_question_instance: if option_id not in options_id_pool: Option.objects.filter(pk=option_id).delete() return instance Tests.py : def create_single_answer_question(company=None): question = Question.objects.create( question_text='some test', level=Question.DifficultyLevel.EASY, company=company, ) for i in range(4): question.options.create( title=faker.name(), ) # mark one option as correct option = Option.objects.filter(question=question).first() option.is_correct = True option.save() return question class TestQuestionByIDAPIView(QuestionBaseTestCase): def setUp(self): super().setUp() self.create_company_group_for_handle_permission(company=self.company, … -
"daemon" directive is duplicate in /etc/nginx/nginx.conf:33 nginx-proxy "daemon" directive is duplicate in /etc/nginx/nginx.conf:33
I am working with nginx-proxy and lets-encrypt I am following this guide https://testdriven.io/blog/django-lets-encrypt/#nginx-proxy-service Other than that I am running another nginx service for my uswgi and written a "run.sh" command the content of my file is #!/bin/sh set -e envsubst < /etc/nginx/default.conf.tpl > /etc/nginx/conf.d/default.conf exec nginx -g 'daemon on;' Content of my default.conf is server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } I know the error clearly indicates that there are 2 daemons running, but I cannot figure out how to fix this issue. I want to run both of them My dockerfile is FROM jwilder/nginx-proxy:0.9 LABEL Carte Blanche LLC COPY vhost.d/default /etc/nginx/vhost.d/default COPY custom.conf /etc/nginx/conf.d/custom.conf COPY ./default.conf.tpl /etc/nginx/default.conf.tpl COPY ./uwsgi_params /etc/nginx/uwsgi_params COPY ./run.sh /run.sh ENV LISTEN_PORT=8000 ENV APP_HOST=app ENV APP_PORT=9000 USER root RUN mkdir -p /vol/static && \ chmod 755 /vol/static && \ chmod +x /run.sh VOLUME /vol/static CMD ["/run.sh"] The folder structure is below