Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending data to external api url django rest_framework [Errno 2] No such file or directory
#My views file class CreateImageInfo(APIView): parser_classes = [MultiPartParser, FormParser] serializer_class = PostCreateUpload def post(self, request, *args, **kwargs): headers = {'Authorization': 'Bearer ' + c} url = 'https://api.logmeal.es/v2/image/recognition/type/{model_version}' file = PostCreateUpload(data=request.FILES) if file.is_valid(): file.save() image = file.data['image'] resp = requests.post( url, files={'image': open(image, 'r')}, headers=headers) return Response(resp.data, status=status.HTTP_201_CREATED) #Serializer File class PostCreateUpload(serializers.ModelSerializer): class Meta(): model = Identified fields = ('timestamp', 'image') #My Models file- class Identified(models.Model): # name = models.CharField(max_length=30) image = models.ImageField(upload_to='media', blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.timestamp ** current error coe displaying is "FileNotFoundError: [Errno 2] No such file or directory: '/images/media/art.onlin_281031686_1095087414692746_398359933098246564_n.jpg'"** -
Django: how to add slug to url tag in django?
i want to add a slug to url in using django, i have tried different slugs but there is something i am missing. <a href="{% url 'tutorials:tutorial' t.tutorial_category.slug t.tutorial_topic_category.slug t.topic.slug t.slug %}">{{t.title}}</a> this is my views.py def tutorial(request, main_category_slug, topic_category_slug, tutorial_slug): tutorial_topic_category = TutorialTopicCategory.objects.get(slug=topic_category_slug) topic = Topic.objects.filter(tutorial_topic_category=tutorial_topic_category) tutorial = Topic.objects.get(slug=tutorial_slug) context = { 'topic':topic, 'tutorial':tutorial, } return render(request, 'tutorials/tutorial.html', context) urls.py path("<slug:main_category_slug>/<slug:topic_category_slug>/<slug:tutorial_slug>", views.tutorial, name='tutorial') -
Using Regex Validators
How can I use Regex Validators in my Django project? (Current using Django 1.11) forms.py class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'order_id','full_name','company','email', 'phone_number','note') To be more specific in 'full_name' , 'company' and 'note' fields I just want to allow digits and letters. In 'email' field want to allow digits , letters, "-" , "_" , "." and "@" characters. And in 'phone_number' field want to digits and "+" , "#" , "()" characters. -
Display media files with Django
I learn Django and I have a problem with display img in settings I add: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "moje_media") and in url.py I add static urlpatterns = [ //routing ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Problem is that img is uploading correctly but I have a problem with display that. For example - in my template I have img tag: <img src="{{MEDIA_URL}}{{film.plakat}}"> But it doesn't display that. I inspect img that and src contain "/media/plakaty/test.jpg". I go to Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ filmy/ login/ [name='login'] logout/ [name='logout'] ^media/(?P<path>.*)$ The current path, media/plakaty/test.jpg, matched the last one. What is wrong? -
return multiple images and their corresponding id in django
I want to send multiple images and their corresponding id from django to react.js. I tried to return dictionary of images with id as key in this format: {id1:image1, id2:image2} but i only recieved this in react.js {id1, id2} and there is no media images in recieved dictionary. How can return multiple images and thier corresponding id in django? -
how to create choices field from Enum Types Django
Enum class # waiting the customer ( not paid ) Waiting = "Waiting" # Waiting to the next ship Pending = "Pending" # on the way Shiping = "Shiping" # Done Done = "Shipped" Order Model How can I make Choices field from the Previous Class class Order(models.Model): customer = models.ForeignKey(User,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) amount = models.PositiveIntegerField() status = models...! -
A better solution for the increasing number game?
I am remaking the question I made here based on the feedback given to me. If there is still something unclear in my question please let me know. Explanation for the game: Increasing number game where the user has to guess before the number is going to stop increasing. This is purely a random chance and is done by clicking on a button by the user. Number is calculated on the server side after each game. Number will be increasing by 0.01 starting from 1.00 until the number calculated on the server side. Solution I have come up with: Running a background process using apischeduler. Executing the number increasing function every 0.1 seconds which adds 0.01 to the current state of number and sends the state result to frontend using Django Channels. I am pulling and updating the state using database queries. When the end result (number) is reached, new number will be calculated and there will be a timer running before new game begins. That all this seems odd considering I am calling a function in the background every 0.1 seconds forever. I can not figure out how to complete the task differently though. Is there a better solution/more … -
How to set allowed characters in Django forms?
I want to set allowed characters for my forms. How can I do this limitation in Django 1.11? forms.py from django import forms from .models import Customer class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'order_id','full_name','company','email', 'phone_number','note') -
Should I use .values_list(), .exists() or something else to check for existence?
I have a model with a string as primary key class Player(models.Model): player_tag = models.CharField(max_length=9, primary_key=True) [...] The player tag is unique to each player, and I retrieve batches of up to 30 player tags before either creating or updating them. However doing so requires me to check if the player tag already exists, and for that I know Django has .exists() method, that checks for the presence of an item inside a queryset. However I figured that would hit the database each time I looked for a player, which sounds less than ideal. I also thought about using a line like this : player_ids = models.Player.objects.values_list('player_tag', flat=True) Which would hit the db once and then I'd check against this list for presence. But I doubt this scales. (The player list can get very lengthy) Is there a better solution for this, something that would allow me to check for the existence of a string primary key while keeping the impact on the database minimal ? -
database design for conditional questions
i'm trying to implement a system where the user select a symptom and then questions related to that symptom will show up , but it must be related to previews answer this is what im thinking for now class Symptom(models.Model) : symptom = models.CharField(max_length=1000) class Question(models.Model) : previous_answer = models.IntegerField() question = models.CharField(max_length=1000) image = models.ImageField('image') symptom = models.ForeignKey(Symptom,on_delete=models.CASCADE) class Answer(models.Model) : answer = models.CharField(max_length=1000) question = models.ForeignKey(Question,on_delete=models.CASCADE) -
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?