Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Auto Create new User for new teanants in django
I'm trying to develop multi tenants web applications using this packages. Every things is working fine, Here one thing is missing that is automatically create new user for new tenants. I know we can create new super user using this command python manage.py tenant_command createsuperuser --schema=schema_name But i want to automatically create new user on basis of information provided by the user -
TestCase testing create order django
I writing testcase to create an order in Django and when I run test it's ok. But, I'm not sure if the testing process is correct. Or have to write anything more. my tests.py In the test of creating an order. class ItemsBuyTestCase(TestCase): def test_buy_items(self): user = self.create_user("test") buy = G(Items) order = create_order([buy], user=user) order.paymentreceived() Thanks. -
how are request handler when we use opencv with django
I am trying to make a Face detection and facial recognition system using Django so, I used OpenCV to handle all recognition thing but I am a bit confused about how the request is handled when we make a request, in views.py for each request does it generate a new OpenCV thread. def index(request): ..... ..... cap = cv2.VideoCapture(0) while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the resulting frame cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows() ........... ......... and if my application is deployed somewhere and a user makes a request, does he able to use this. what will happen if a user makes a request when the Django application is deployed somewhere ? -
Is it okay to use the same working directory for development and production in docker container?
I am developing a Django project. I am new to Docker and other things related to it. I was wondering whether it is right to use the same working directory for development and production. Thanks for your time and consideration. -
How to properly submit modal forms from django with ajax?
Here I have a modal form in my template.I want to assign my group to the user from this modal form. After submitting the form I want to show the updated results in the template without refresh. For this I tried like this. But the problem here is it performs all the task pretty good but it doesn't close the modal form after submit but the submitted group goes to the ul list without refresh. Also I want to know instead of rendering html data and doing stuff like this(i think it is not good practice) Will it be better to send JsonResponse from django view to the template instead of html.If it is the good practice how can I do this and How can I handle the json data in ajax call in the template.I am very new to ajax/jquery stuff so any suggestions? def assign_group_to_user(request, pk): group = request.POST.get('group') user = get_object_or_404(get_user_model(), pk=pk) user.groups.add(group) return render(request, 'dashboard/ajax_groups_list.html') modal form <div class="modal--group"> <div class="modal fade" id="addGroup" tabindex="-1" role="dialog" aria-labelledby="addGroupTitle"> <div class="modal-body"> <form method="post" id="group-ajax-form" data-url="{% url 'dashboard:assign_group' user.pk %}"> {% csrf_token %} <div class="form-group"> <label>Group Name</label> <select name="group" class="form-control> {% for group in groups %} <option value="{{group.pk}}">{{group.name}}</option> {% endfor … -
select values from jsonfield in query set
class EMI(models.Model): emi = JSONField(default=dict) json values {"1": {"days": 1, "interest": 15, "penalty": 0.01, "amount": 32.0}, "2": {"days": 6, "interest": 6, "penalty": 0.01, "amount": 80.0}} and i want ammount in values -
How to extend the fire-base token expiry timings in django are python am using the drf firebase auth
am using fire-base auth user for login and register in my website how to extend the token expire for fire base token in django i tried by creating custom token authentication but its not useful for me -
Pillow cropper resizing instead of cropping
I am using a JQuery image cropper which uses Pillow on the back-end to crop and resize the images. I have this code working in a test project but I cannot get it to work correctly in my main project. Currently, when I crop the image it should grab the region and crop it 200x200 but what it seems to be doing is resizing the image to random aspect ratios, making it very blurry, and surrounded by black. It looks to be 200x200 but the image is very small inside the 200x200 black region. Forms.py: class UserUpdateForm(forms.ModelForm): """ Employee update form, related to: :model: 'auth.Employee', :model: 'auth.Groups' """ phone = forms.CharField(min_length=10) email_notifications = forms.BooleanField(required=False) sms_notifications = forms.BooleanField(required=False) x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = Employee fields = [ 'username', 'first_name', 'last_name', 'email', 'phone', 'badge_num', 'email_notifications', 'sms_notifications', 'image', 'x', 'y', 'width', 'height', ] widgets = { 'employee_type': forms.HiddenInput(), 'image': forms.FileInput(attrs={ 'accept': 'image/*' # this is not an actual validation! don't rely on that! }) } def save(self, commit=True): photo = super(UserUpdateForm, self).save() x = self.cleaned_data.get('x') print(x) y = self.cleaned_data.get('y') print(y) w = self.cleaned_data.get('width') print(w + x) h = self.cleaned_data.get('height') print(h + y) … -
Alternative of Flower for Celery stats if broker is AWS SQS
Flower can't be use if broker is aws SQS, for aws SQS for celery stats what can be used. -
'str' object has no attribute 'save' Django
class AgentForm(forms.ModelForm): def __init__(self, *args, **kwargs): # agents = dashboard_userlink.objects.filter(username__in=Subquery(task_router_calldetail.objects.values('agent').distinct())).values_list('username').annotate(full_name=Concat('first_name', Value(' '),'last_name')).order_by('first_name') agents = dashboard_userlink.objects.values('username').distinct().values_list('username').annotate(full_name=Concat('first_name', Value(' '),'last_name')).order_by('first_name') for i in agents: agent_name = i[0] agent_value = i[1] if agent_value == ' ': agent_value = agent_name agent_value.save() agent_list = [('','Select')] + list(agents) super(AgentForm, self).__init__(*args, **kwargs) self.fields['agent'] = forms.ChoiceField( choices=agent_list ) -
Get the values for selected multiple checkbox in Django
I am building an app with django. Now i am facing a problem with checkbox. I can retrive the values from request.POST.get(checkbox[]). But its comming with a list. Then i am making a for loop to use the slug to get the prices but here i faced like how to store it with a separate variable for each check box. As it is in loop, for different values with different variables is not possibe? How could i do it ? In my model I have one table with extras. It has SSL, SECURITY, BACKUP. If the check box of SSL and SECURITY selected then by the slug I will get the price. But i want that to add to Order model which has a fields like SSL and SECURITY . I am getting totaly confused. How should I make the model architecture. With Hosting user can buy SSL, SECURITY, BACKUP or any of them. def checkout(request): if request.method == "POST": extras_slugs = request.POST.get("checkbox[]") for slug in extras_slugs: -
process multiple csv file in python
I have multiple csv file in the following manner: items | per_unit_amount | number of units book 25 5 pencil 3 10 .. How can I calculate Total amount of the bills for all csv file in multi threaded manner ? -
My custom validators are not working django
def validate_fname(value): if value == " ": raise serializers.ValidationError("First name may not be blank") return value class UserSerializer(serializers.Serializer): username = serializers.CharField(max_length = 50, required=True, validators=[UniqueValidator(queryset=User.objects.all(),message="This username is already taken")]) first_name = serializers.CharField(validators=[validate_fname]) last_name = serializers.CharField(required=True) email = serializers.EmailField(max_length = 50, required=True, validators=[UniqueValidator(queryset=User.objects.all(),message="This email is already taken")]) password = serializers.CharField(required=True) pass2 = serializers.CharField(required=True) -
How to render nested formset and save in django?
Problem: I have a problem with third form that has nested form at first it renders properly when I delete any child form that nested from all the form gets deleted. how can I fix that End Goal: I wanted to built signup form that consists of three forms first form is basic login info, second form can have multiple instances of the single form where the user can add more form or remove it. and third form if nested from where the user also can add from or remove it. all these in under a single submit button. What I have done: At this point i'm able to build all of the forms and stored first two forms that are basic signup info and second form that have multiple instances. # model.py class Vendor(BaseModel): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) address = models.CharField(max_length=100) mobile_no = models.CharField(max_length=12) gst = models.CharField(max_length=20) code = models.CharField(max_length=20) def __str__(self): if (self.user.first_name != None): return self.user.username else: return self.user.first_name # Material/s that vendor can process class VendorMaterial(BaseModel): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) material = models.ForeignKey(Material, on_delete=models.CASCADE) class VendorProcess(BaseModel): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) process = models.ForeignKey(ProcessType, on_delete=models.CASCADE) def _get_full_name(self): return self.process full_name = property(_get_full_name) def __str__(self): return self.process.name … -
unindent does not match any outer indentation level in the custom user model
I try to add a custom column in the Django default user model, what annoying me was there is an error pops up to me, "unindent does not match any outer indentation level". Here is the code below email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) keyStore = models.CharField(max_length=32,unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) The error is pointing at the second row the keyStore. How can I fix that? -
Django, Modeling Related Dates
I'm trying to make a Django app that tracks activities. Each activity has both a start and end date. I would like to have these dates be able to relate to one another. This would look like activity 1 would end on 1/1/2020 and activity 2 would start on 1/1/2020. If I were to then update activity 1 end date to 1/7/2020, I would like activity 2 to then start on 1/7/2020. I think I would want an Activity model and a Date model. I can relate a date to an activity, I just don't know how to model the waterfall effect of relating a date to another date in the same model, while relating each date to the appropriate activity instance. I'm also happy to split the dates into 2 models (StartDate, EndDate) if that makes it cleaner. Open to any solution. Thank you in advance for any help. -
What is the best way to implement Django 3 Modal forms?
I appreciate it if somebody gives the main idea of how to handle submission/retrieval form implementation in Bootstrap modals. I saw many examples on google but it is still ambiguous for me. Why it is required to have a separate Html file for modal-forms template? Where SQL commands will be written? What is the flow in submission/retrieval forms (I mean steps)? What is the best practice to implement these kind of forms? I'm fairly new to Django, please be nice and helpful. -
which should come first creating a django user or a stripe payments charge?
I am using Django and stripe checkout. When someone new comes to the site, wanting to join and pay by credit card, I need to create a new user (ie setup a user name and password) as well as charge them (via stripe's API). From a code and UX perspective, which should come first? Or, better, can I do both in one step? Note: various web tutorials discuss these separately but never together. -
How to use ci.yml to declare env variables to be used in python?
-in gitlab-ci.yml variables: SECRET_KEY: secret_key DB_NAME: camel_backend DB_USER: postgres DB_HOST: mdillon-postgis DB_PORT: 5432 DB_PASSWORD: '' -in django DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } } Django doesn't seem to pick up the variables declared on CI when running pipeline. How do I properly declare the env variables on testing? -
How can i create multiple objects in one request ?, in which each objects have file field
I'm trying to create multiple documents objects, when i send request without file filed it create multiple objects, but i don't know how to send multiple objects with filefiled from 'form-data' of postman or from raw data in json format. Please suggest me what can i do for this. My Document Model is: class Document(models.Model): employee = models.ForeignKey(EmployeeInfo, on_delete = models.CASCADE) document = models.CharField(max_length=255, help_text='passport') date_added = models.DateField() valid_until = models.DateField(null = True, blank = True) detail = models.TextField(null=True, blank=True) attachment = models.FileField(upload_to='attachments', null=True, blank=True) for this my view is : class DocumentAPICreateView(CreateAPIView): serializer_class = DocumentSerializer permission_classes = [IsAuthenticated] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many = True) if serializer.is_valid(): self.perform_create(serializer) headers = self.get_success_headers(serializer.data) response = create_response(True,data = serializer.data) return Response(response, status=status.HTTP_201_CREATED, headers=headers) else: response = create_response(False, err_name = serializer._errors) return Response(response, status = status.HTTP_400_BAD_REQUEST) when i send data without attachment it works like this: [{ "employee":38, "document":"Trial2", "date_added":"2019-12-10" }, { "employee":38, "document":"Trial3", "date_added":"2019-12-10" }] How can i send objects list with attachment field? -
Accessing a BoundField on a Form instance
>>> form = ContactForm() >>> print(form['subject']) <input id="id_subject" type="text" name="subject" maxlength="100" required> I have taken this from the documentation, however i am not sure how it is possible to access a Form instance like a dictionary from form['subject'] Does anyone know how this is implemented? -
Django inline formset use for ManyToMany field
I'm trying to get an inline formset working to display child class fields I can edit in a form. I've been following Working with nested forms but there's some aspect I don't understand as the inline formset render produces delete checkboxes but no select element. I was using ManyToManyField without the through parameter but it seems I need to explicitly define NotebookTag and use the through parameter to create an inline formset. models.py class Tag(models.Model): name = models.CharField(max_length=63) class Notebook(models.Model): title = models.CharField(max_length=200) tags = models.ManyToManyField(Tag, through='NotebookTag') class NotebookTag(models.Model): notebook = models.ForeignKey(Notebook, on_delete=models.PROTECT) tag = models.ForeignKey(Tag, on_delete=models.PROTECT) views.py from .models import Notebook, Tag, NotebookTag from django.forms.models import inlineformset_factory TagFormset = inlineformset_factory(Tag, Notebook.tags.through, fields=('tag',)) class NotebookUpdateView(UpdateView): model = Notebook template_name = 'notebook_edit.html' fields = '__all__' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) if self.request.POST: context["children"] = TagFormset(self.request.POST) else: context["children"] = TagFormset() return context Essentially I want to be able to edit or add new tags to associate with a Notebook -
Django soft form-validation for fuzzy matches. Allow validation to be skipped on second form submit
I have a Django form which I would like to 'soft-validate'. By soft-validation I mean: on the first submit attempt, the clean_name() methods raise ValidationError and the View re-renders the form with a field error displayed informing the user that this may be a duplicate entry; but on the next submit, the ValidationError is ignored and the form is saved. Is there any way in the Form class to detect the number of submit attempts, and conditionally toggle the validation? FYI my usage case for soft-validation is: - checking existing records for near-matches on certain CharFields. I am using Postgres trigram similarity for this. # views.py class addFoo(LoginRequiredMixin, IsStaffMixin, CreateView): model = Foo template_name = "Foo/Foo_form.html" form_class = FooUpdateForm # forms.py class FooUpdateForm(forms.ModelForm): class Meta: model = Foo fields = [ "id", "name", ... ] def clean_name(self): name = self.cleaned_data["name"] QS = ( Foo.objects.annotate(similarity=TrigramSimilarity("name", name)) .filter(similarity__gt=0.3) .exclude(id=self.instance.id) .order_by("-similarity") ) names = list(QS.values_list("name", flat=True)) if len(names) > 0: message_1 = f"This name is similar to {len(names)} other records. Are you sure it is not a duplicate?</br>& raise forms.ValidationError( mark_safe(message_1 + ("</br>&emsp;").join(names)) ) return name My thoughts I've tried toggling a hidden form-field from the clean method, but the toggled state doesn't … -
Run .env file in django app with python-dotenv when starting shell
I'm trying to use python-dotenv to run the .env file when running ./manage.py shell. But .env isn't run when I start shell. Nothing different than normal happens. What I've done: installed python-dotenv with pip install python-dotenv in my virtual environment added a .env file in the same directory as my project settings.py Also added below to settings.py: from dotenv import load_dotenv load_dotenv() For context, my .env looks like: export PYTHONSTARTUP=`pwd`/.pythonrc.py echo "environment variables set" And I'm exporting .pythonrc.py so I can do some imports when shell is loaded. I'm pretty new to django. Am I missing something obvious? -
USER Object is not iterable, pylor or haystack error
Traceback (most recent call last): File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/agp/PycharmProjects/AGP/AGP_2_7/artifacts/views.py", line 352, in upload artifact, admin = saveArtifact(request.POST, artifact_object_type, artifact_form, request.user)# here is error File "/home/agp/PycharmProjects/AGP/AGP_2_7/artifacts/views.py", line 519, in saveArtifact specific_form.save() # here is error File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/forms/models.py", line 458, in save self.instance.save() File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/db/models/base.py", line 790, in save_base update_fields=update_fields, raw=raw, using=using, File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/signals.py", line 52, in handle_save index.update_object(instance, using=using) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/indexes.py", line 284, in update_object backend.update(self, [instance]) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/backends/solr_backend.py", line 60, in update docs.append(index.full_prepare(obj)) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/indexes.py", line 208, in full_prepare self.prepared_data = self.prepare(obj) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/indexes.py", line 199, in prepare self.prepared_data[field.index_fieldname] = field.prepare(obj) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/fields.py", line 279, in prepare return self.convert(super(IntegerField, self).prepare(obj)) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/fields.py", line 88, in prepare values = self.resolve_attributes_lookup(current_objects, attrs) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/fields.py", line 115, in resolve_attributes_lookup values.extend(self.resolve_attributes_lookup(current_objects_in_attr, attributes[1:])) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/fields.py", line 115, in resolve_attributes_lookup values.extend(self.resolve_attributes_lookup(current_objects_in_attr, attributes[1:])) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/fields.py", line 107, in resolve_attributes_lookup for current_object …