Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Grouping Wagtail CMS streamfield fields?
First of all, I wish everyone a good day. I want to group blocks that I created with StreamField. I am attaching an example video and image below. You can view the image here. https://youtu.be/VMfxVCGarf4 Thank you for your help, best regards. What do I want to do? All component list Sub column (Component #1) Sub column (Component #2) Sub column (Component #3) All html blocks Sub column (HTML block #1) Sub column (Component #2) Sub column (Component #3) -
best way to use docker push command
I have just managed to containerized existing Django project. Now, I am pushing it to the docker-hub but, notice some 500mb file is getting pushed on the server. does 500mb is normal while pushing it to the docker-hub or I have to ignore some of the fie like we do with .gitignore. -
Get anchor and all params in request path
For a development with django, I try to get the parameters of my url. my path : http://127.0.0.1:8000/categories/candy#bubblizz candy is my view avec #bubblizz is my id anchor. A lot of documentation on request items but impossible to find how to get the anchor {{ request.build_absolute_uri }} => http://127.0.0.1:8000/categories/candy {{ request.get_full_path }} => /categories/candy {{ request.path }} => /categories/candy {{ request.META.PATH_INFO}} => /categories/candy The goal is to test the presence of the anchor in the url. {% if bubblizz in request.anchor %}Yeah{% endif %} Does anyone have an idea? Or documentation that might help? Thanks -
Django self.request.FILES.getlist
So I have changed the input's name attribute to some custom name, but the view calls form_invalid method. Why my Form isn't saving (validating)? html: <tr> <th><label for="id_photo">Image:</label></th> <td> <input type="file" name="custom_photo_name" accept="image/*" required id="id_photo" multiple> </td> </tr> the form: class DateForm(forms.ModelForm): photo = forms.ImageField(required=False) class Meta: model = Date exclude = ('user',) the view: class UpdateDateView(LoginRequiredMixin, UpdateView): model = Date form_class = DateForm template_name = 'app/form/date_edit_form.html' @transaction.atomic def form_valid(self, form): date = form.save() self.request.FILES.getlist('custom_photo_name') # this returns an empty list [] return super().form_valid(form) Doesn't the self.request.FILES takes the values according to name attribute? Why can't I reach my files? -
Django serializer validation
I am using serializers for validation. when i am sending key with name ip_port which is a list in form-data postman then response is coming 'This field is required' for ip_port key. Also i am attaching an image of postman where i am getting the response. Please help anyone and thanks in advance.postman response while testing POST api views.py def post(self,request,format=None): data=request.data serializer=UserRequestFormSerializer(data=data) if serializer.is_valid(raise_exception=True): # breakpoint() serializer.save(user=self.request.user) # print(serializer.data) sdata=serializer.data return Response({'detail':'User Request Form created successfully','created_data':sdata},status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) serializers.py class UserRequestFormSerializer(serializers.ModelSerializer): ip_port = IPPortSerializer(many=True) district=serializers.CharField(source='user.district',read_only=True) class Meta: model=UserRequestForm fields='__all__' read_only_fields=['user','district'] def to_representation(self, instance): data = super().to_representation(instance) if instance.form_status == "REJECT": data['rejection_data'] = RejectionTableSerializer(instance.rejectiontable_set.last()).data return data def create(self, validated_data): ipport=validated_data.pop('ip_port') user=UserRequestForm.objects.create(**validated_data) if ipport: ls=[] for i in ipport: ls.append(IPPort.objects.create(**i)) user.ip_port.set(ls) return user models.py class UserRequestForm(models.Model): #All Foreign keys: observer_account_type = models.CharField(max_length=200, choices=ACCOUNT_TYPE, blank=True,default='USER') decision_taken_by=models.ForeignKey(User,on_delete=models.CASCADE,related_name='userrequestform_decision_taken_by',blank=True,null=True) user=models.ForeignKey(User,on_delete=models.CASCADE) ip_port=models.ManyToManyField(IPPort) #to be filled by the user: sys_date=models.DateField() sys_time=models.TimeField() target_type=models.CharField(max_length=200,choices=TARGET_TYPE) case_ref=models.CharField(max_length=200) case_type=models.CharField(max_length=200) request_to_provide=models.CharField(max_length=200,choices=REQUEST_TO_PROVIDE) mobile_number=models.BigIntegerField(validators=[mobile_regex_validator]) cell_id=models.CharField(max_length=200) imei=models.CharField(max_length=200) select_tsp=models.ForeignKey(Tsp,on_delete=models.PROTECT) duration_date_from=models.DateField() duration_date_to=models.DateField() duration_time_from=models.TimeField() duration_time_to=models.TimeField() user_file=models.FileField(upload_to='user_doc',blank=True,null=True) #to be filled by TSP and CYBERDOME form_status=models.CharField(max_length=200,choices=FORM_STATUS,blank=True,null=True,default='PENDING') admin_status=models.CharField(max_length=200,choices=FORM_STATUS,blank=True,null=True,default='PENDING') #for tsp replie requested_date=models.DateField(blank=True,null=True) replied_date=models.DateField(blank=True,null=True) #for cyberdome view approval_or_reject_date=models.DateField(blank=True,null=True) approval_or_reject_time=models.TimeField(blank=True,null=True) #For TSP to upload file after approval tsp_file=models.FileField(upload_to='tsp_doc',blank=True) class Meta: ordering = ('id',) def __str__(self): return str(self.mobile_number) class IPPort(models.Model): ip=models.CharField(max_length=200,validators=[ip_regex_validator]) port=models.IntegerField() date_from=models.DateField(blank=True,null=True) date_to=models.DateField(blank=True,null=True) time_from=models.TimeField(blank=True,null=True) … -
Django Storages (GCP) returns NULL if the app is deployed in Cloud Run
I am using Django Storages to upload images on GCP's cloud storage bucket and I accomplished this on localhost by following these steps - Created a private bucket on Cloud Storage. Created a service account with Storage Admin privileges and also generated a JSON key. Installed Django Storages for GCP and Pillow. Created relevant environment variables like GOOGLE_APPLICATION_CREDENTIALS, GOOGLE_CLOUD_PROJECT and GS_BUCKET_NAME. Wrote a POST & GET request and it works like a charm on local machine. However, when I deployed this on Cloud Run I am able to upload the images but I get NULL instead of the image's Authenticated URL in response while fetching the image via GET request. As, Cloud Run uses Compute Engine Default Service account So I decided to give it a Cloud Storage Admin permission and then I tried again but still no luck. How can I make this work? -
Encrypt Django auth User model's fields
I am trying to encrypt my username and email field in Djago's Default Auth model using a Proxy Model method but so far with no luck. Here is what I have attempted so far: class UserManager(models.Manager): def from_db_value(self, value, expression, connection): if value is None or value == '': return value # decrypt db value and return return decrypt(value) def get_prep_value(self, value): # prepare value to be saved to the database. return encrypt(str(value)) class CustomUser(User): objects = UserManager() class Meta: proxy = True def print_value(self, value): print('test', value) def save(self, *args, **kwargs): self.user = self.print_value(self.user) super().save(*args, **kwargs) I am trying to overwrite the User model with Proxy model and a custom Model manager. Any tips whether how can I achieve this would be really appreciated. -
How i can create a muti value filed without manytomany field in django?
I have a model: class People(models.Model): family = models.CharField(null=True) phone_numbers = ? How i can implement phone_numbers for some phone numbers. I think ManyToManyField is not a good idea for doing this. What is best practice for this? -
How can i do my url flexible in Django 1.11?
In my project with django I should do a site with flexible url. For instance: 'mysite.com/register/kj-1k-32-mk' When someone write some other things after register/ I want to redirect them to my site. How can I redirect them. What should my urls.py looks like? urls.py from django.conf.urls import url from django.contrib import admin from olvapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register/(?P<pk>\d+)',views.guaform,name='custform'), ] When I do like above, the part after register/ can't begin with a letter. -
Django exists query not work in if and else clause?
In given below if Medicine table consists medicine_name then query execute fine, but when medicine name doesn't exist then error is occured. Matching Query Doesn't Exists if Medicine.objects.filter(medicine_name=m.medicine_name).exists(): return Response({"message": "Successfully Recorded"}) else: return Response({"message": "Not Recorded"}) -
Deploying React front end with Django session based auth doesnt work over HTTPS
So I have a working LOCAL Twitter clone called Hater but cant deploy front end b/c I cant access secured Cookies(https://github.com/mustafabin/hater) I used Django's built-in Session-based auth I have middleware all set up LOGIN VIEW @method_decorator(csrf_protect, name="dispatch") class LoginView(APIView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): data = self.request.data username = data['username'] password = data['password'] try: user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return Response({'success': 'User authenticated'}) else: return Response({'error': 'Error Authenticating'}) except: return Response({'error': 'Something went wrong when logging in'}) SIGN UP @method_decorator(csrf_protect, name="dispatch") class SignupView(APIView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): data = self.request.data username = data['username'] password = data['password'] re_password = data['re_password'] tag = data['tag'] try: if password == re_password: if User.objects.filter(username=username).exists(): return Response({"error": "Username already exists"}) else: if len(password) < 6: return Response({"error": "Password must be at least 6 characters"}) else: user = User.objects.create_user( username=username, password=password) user = User.objects.get(id=user.id) user_profile = User_profile.objects.create( user=user, name=username, tag=tag) return Response({'success': "User created successfully"}) else: return Response({'error': "Passwords do not match"}) except: return Response({"error": "Something went wrong signing up"}) I'm aware some of these settings are redundant but ur man got desperate CORS_ORIGIN_ALLOW_ALL = True CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_HTTPONLY = False CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE … -
Image Fields In ModelForms in Django
I want to create a modelform that follows the model below but I do not know how to create an foreign key and imagefield in modelforms please help me thanks this is my model -
No module named 'rest_framework'
I am trying to deploy my django project on heroku but I'm facing this error of rest framework even though I've installed and it shows requirements already satisfied . and some other errors which I cannot understand $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/tmp/build_048f019e/manage.py", line 22, in <module> remote: main() remote: File "/tmp/build_048f019e/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site- packages/django/core/management/__init__.py", line 419, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site- packages/django/core/management/__init__.py", line 395, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.9/site- packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.9/site- packages/django/apps/registry.py", line 91, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.9/site- packages/django/apps/config.py", line 224, in create remote: import_module(entry) remote: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'rest_framework' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: … -
SSL implementation on custom port for django application using nginx
I am trying to host multiple django applications on the same IP. I have an django application on hosted on specific port 8001 with domain name (domain_name.com). Now on accessing https://domain_name.com, application runs pretty well, But on http://domain_name.com , another applciation hosted in port 80 loads. On accessing 'domain_name.com' how can i redirect to port 8001 for both http and https requests ? My nginx conf for domain is as below. server { listen 8001; server_name erostreasures.com www.erostreasures.com; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:/run/agmarket.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/erostreasures.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/erostreasures.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } -
Private chat using django
Guys I want to create a private chat feature for my webapp. I referred numerous blog, everyone of them is pointing to creating a room and having group chat. Can anyone help me any blog,video or way to build a individual chat feature using django? -
Matching Query Doesn't Exists in Django?
I will Perform following this POST request in my views.py file if Medicine.objects.filter(medicine_name=m.medicine_name).exists(): if existing > 0: m.save() Medicine.objects.filter(id=p_key).update(no_of_medicine=existing) return Response({"message": "Successfully Recorded"}) else: return Response({"message": "Not much Medicine Stored"}) else: return Response({"message": "Medicine is not Stored"}) The code is working fine if Medicine Exists . if Medicine not exists give me above Exception . Please anyone can help me -
how can i filter my model to get user answer for a current question
I have two models the Answer model and the Question model. when user post the question i want another user to be able to post an answer in the current question similar to stack overflow, i know using this method: MyModel.objects.all() will returns all the answers from all question to a each question, that's is not what i want. How can i do this in Django please ? my model class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.user) class Answer(models.Model): user = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, null=False, blank=False, on_delete=models.CASCADE) def __str__(self): return str(self.user) i want to pass user's Answer into this viewQuestion view my view def viewQuestion(request, pk): question = Question.objects.get(id=pk) context = {'question':question} return render(request, 'viewQuestion.html', context) class My_Answer(LoginRequiredMixin, CreateView): model = Answer fields = ['answer'] template_name = 'answer.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Answer, self).form_valid(form) -
How can I host Django with celery on cpanel?
I am confused if I can host my django with celery project on cpanel.If yes, How? -
django multiple table query
I have a form for filling out lessons that I want to limit who the students can select as their teacher to only confirmed connections. I have three models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True, blank=True) class Lesson(models.Model): user = models.ForeignKey(User, related_name='fencer', on_delete=models.SET_NULL, null=True, blank=True) teacher = models.ForeignKey(Fencer, related_name='instructor', on_delete=models.SET_NULL, null=True, blank=True) lesson_date = models.DateField(default="1900-01-01") title = models.CharField(max_length=100, null = True, blank=True) description = models.TextField(null=True, blank=True) class Connection(models.Model): student = models.ForeignKey(User, related_name='student', on_delete=models.CASCADE, blank=True) teacher = models.ForeignKey(User, related_name='teacher', on_delete=models.CASCADE, blank=True) student_accepts = models.BooleanField(default=False) teacher_accepts = models.BooleanField(default=False) @property def connected(self): if self.student_accepts == True and self.teacher_accepts == True: return True else: return False My form so far is: class LessonForm(ModelForm): class Meta: model = models.Lesson #fields = () fields = '__all__' def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['teacher'].queryset = Users.objects.filter() # the best I have so far How do I filter the User model based on the link made in the Connection model? Maybe I'm overcomplicating this or is there a better way? Thank you in advance -
Django import export - ManyToManyfield
I have a ManyToMany field in my models. I want to import data and enter into that field. My Resources.py:- class ClinicResource(resources.ModelResource): language = fields.Field(column_name='language',attribute='language', widget=ForeignKeyWidget(Language, 'code')) country = fields.Field(column_name='country',attribute='country', widget=ClinicCountryForeignKeyWidget(model = Country, field ='name')) clinic_languages = fields.Field(widget=ManyToManyWidget(ClinicLanguages, field='name')) class Meta: model = Clinic fields = ('code', 'name', 'city', 'score') exclude = ('id',) import_id_fields = ('code', 'name', 'city', 'score', 'language', 'country') my Models.py:- class Clinic(models.Model): code = models.CharField(max_length= 10, blank= False, null= False) name = models.CharField(max_length= 256, blank= False, null= False) slug = models.SlugField(null= True, blank= True) # country = models.CharField(max_length= 256, blank= False, null= False) city = models.CharField(max_length= 256, blank= False, null= False) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='allcliniccountry', blank= True, null=True) score = models.FloatField(blank= False, null= False, default= 2, validators=[MinValueValidator(min), MaxValueValidator(max)]) language = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='allclinicslanguage', blank= True) # about = models.TextField(blank= True, null= True) clinic_languages = models.ManyToManyField(ClinicLanguages, related_name='clinic_language', blank= True) about = tinymce_models.HTMLField(blank= True, null= True) created= models.DateTimeField(auto_now=True) status = models.CharField(max_length= 30, choices= SIZE_CHOICES, default= 'pending', blank= False, null= False) NOTE THE clinic_languages field, this is what I want to import -
Install grpcio via pip: "legacy-install-failure"
I want to install grpcio with pip(version 1.35). But I get this error: note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> grpcio I tried to install python-dev or wheel, but it did not work. My python version = 3.10 Ubuntu = 22.04 -
Django does not create foreign key in sqlite table
I use sqlite in a Django project. I created a model called Employee, and then Education, but I forgot to add a foreign key to Employee. When I found the problem, I added the foreign key: class Education(models.Model): employee=models.ForeignKey(Employee, on_delete=models.CASCADE), But when run manage.py makemigrations, it says nothing changed. So I tried to delete the sqlite database file, delete all migrations and tried to create a new database. It still say nothing changed! the sqlite database file is created, with 0 size! What is happening to django? -
Django-How can I upload image to a Model, without that field being present in the ModelForm
I am trying to build an image steganography application and for the encoding part I have a form with two fields, one for image and one for the message that is to be encoded. The encoding part takes place in a views.py, but I do not seem to manage how to upload the encoded image in the ImageModel in order to use it later for the decoding part. 1. If I include image_e in the form as a hidden field, I get an error that it needs to be submitted 2. If somehow the form is being submitted, the model contains only the two fields present in the form, 'image' and 'message', and for 'image_e' i get None or the default if i have that option 3. Right now, if I fill the form I get the defaults for all the fields I actually only need 'image_e' stored, but I thought that if I inherit all of the fields from the model it would be easier. I am a beginner in Django and this is my first more complex application. models.py class Image(models.Model): image = models.ImageField(upload_to='images', default='default.png') message = models.CharField(max_length=200, default=1) image_e= models.ImageField(upload_to='encoded', blank=True) forms.py class EncodeForm(forms.ModelForm): #method= forms.CharField(label='How would … -
Django models - how to assign as ForeignKey
My lab has a models.py as below: class Book(models.Model): isbn = models.CharField(max_length=10, unique=True) name = models.CharField(max_length=100) published_year = models.IntegerField() total_qty = models.IntegerField() current_qty = models.IntegerField() max_duration = models.IntegerField() author = models.ForeignKey(Author, on_delete=models.PROTECT) category = models.ForeignKey(Category, on_delete=models.PROTECT) def __str__(self): return self.name class BookCopy(models.Model): class Status: AVAILABLE = 1 BORROW =2 LOST = 3 barcode = models.CharField(max_length=30, unique=True) buy_date = models.DateField(null=True, blank=True) status = models.IntegerField() book = models.ForeignKey(Book, on_delete=models.PROTECT) def __str__(self): return self.barcode class User(models.Model): username = models.CharField(max_length=30, unique=True) fullname = models.CharField(max_length=100, null=True) phone = models.CharField(max_length=10, null=True) def __str__(self): return self.fullname class BookBorrow(models.Model): class Status: BORROWING = 1 RETURNED = 2 borrow_date = models.DateField() deadline = models.DateField() return_date = models.DateField(null=True) status = models.IntegerField() book_copy = models.ForeignKey(BookCopy, on_delete=models.PROTECT) book_name = models.ForeignKey(Book, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) And i wrote the api for borrow_book function like below: @csrf_exempt def muon_sach(request): body = request.POST username = body.get('username') barcode = body.get('barcode') user = User.objects.filter(username=username).first() bookcopy = BookCopy.objects.filter(barcode = barcode).first() if not user: return HttpResponse(json.dumps({ 'error':"Nguoi dung khong ton tai" })) if not bookcopy: return HttpResponse(json.dumps({ 'error':"ma sach khong ton tai" })) book_borrow = BookBorrow() # resp = [] book_borrow.user = user book_borrow.book_copy = bookcopy book_borrow.borrow_date = datetime.now() book_borrow.deadline = datetime.now() + timedelta(days=bookcopy.book.max_duration) book_borrow.status = BookBorrow.Status.BORROWING book_borrow.book_name … -
How to display a list of search results in Django 4
I'm writing a Django app to manage sales leads. From the template that lists a page of leads, I want to give the user the ability to search all leads using first name and last name as the search criteria. When I type in a last name and press enter, the page flickers but remains on the same page rather than the template I created to list the search results. My views, urls, and templates are below. What have I missed? views.py class LeadsListView(ListView): model = Lead template_name = 'leads/list.html' context_object_name = 'leads_list' paginate_by = 10 def get_queryset(self): return Lead.objects.order_by('id') class LeadsSearchResultsView(ListView): model = Lead context_object_name = 'search_results' template_name = 'leads/search_results.html' paginate_by = 10 def get_queryset(self): query = self.request.GET.get('q') return Lead.objects.filter( Q(last__icontains=query) | Q(first__icontains=query) ) urls.py from django.urls import path from .views import LeadsListView, LeadsDetailView, LeadsCreateView from .views import LeadsSearchResultsView app_name = 'lead' urlpatterns = [ path('', LeadsListView.as_view(), name='list'), path('<int:pk>/', LeadsDetailView.as_view(), name='detail'), path('', LeadsCreateView.as_view(), name='create'), path('', LeadsSearchResultsView.as_view(), name='search_results'), ] The template that (successfully!) lists the leads, list.html: {% extends 'base.html' %} {% block content %} <nav aria-label="Page navigation example"> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% …