Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count of values between a certain range for columns of dataframe pandas and render from views.py as dictionary to Django html file
I am new to Python and Django. I need to calculate count values over a range, for dataframe columns and render it as a dictionary object so that I can view it as Django html. I don't know how to do so. I tried to see if I can use histrogram but could not find ways to get output in below format. Similarly I can see that Pandas has Cut function but it looks like it adds against an column. Below are columns from dataframe. In all I have 1190 records in each columns, these are basically percentages of deviations observed. Symbol Date Col1 Col2 XXX 16-02-2020 -0.67 -3.69 XXX 17-02-2020 1.18 4.47 XXX 18-02-2020 -3.02 -0.21 XXX 19-02-2020 -2.15 -0.64 XXX 20-02-2020 4.32 0.40 XXX 21-02-2020 3.89 4.73 . . . What I want to see is output as below. This will be one at a time. i.e Show output for Col1 if selected from list or col2 or col3 so on and so forth. Range Count Total Records More than 3% 7 1190 Between 2% and 3% 9 1190 Between 1% and 2% 97 1190 Between 0% and 1% 433 1190 Between 0% and -1% 528 1190 Between … -
Best way to hot-swap between two APIs in a Django application?
I am not looking for any direct code answers, merely some suggestions or examples. I am pretty new to Django, so I would love to get pointers rather than solutions :) I suppose this is a back-end task, but could also be front-end if someone points me to right location. I want to create a service, that is robust, such that if one API fails, it uses an counterpart API that does the same action. For instance if I use Sendgrid, and it fails, it reverts to using Amazon SES, MailGun or something similar.. The failing part is what I am puzzled about. How do I check that the API failed or is too slow to respond, for the service to redirect to the other API? Is there a good paper or documentation for a "hot-swap" mechanism, if one service is unresponsive? The goal is to makke the user's not wait around or receive error messages, butthat the service just runs at all times. -
Cannot access backend with nginx container
I have a multi container app with an nginx container. I cannot access backend with this config. "Site cannot be reached" App is running locally. This config works without using nginx as a container but when I try use it in a container I cannot access the backend. Why can't I reach my backend using nginx container? Here's my config upstream django { ip_hash; server django:8000; } upstream nuxt { ip_hash; server nuxt:3000; } server { # the port your site will be served on listen 80; # the domain name it will serve for server_name $SERVER_NAME; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /static/ { alias /static/; } location / { proxy_pass http://nuxt; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; } location ~ /(api|admin|static)/ { proxy_pass http://django; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; } } Docker-compose django: container_name: django build: context: ./backend dockerfile: scripts/dev/Dockerfile env_file: .env environment: - DEBUG=True command: > sh -c "./wait-for-it.sh db:5432 && ./autobets/manage.py collectstatic --no-input && ./autobets/manage.py makemigrations && ./autobets/manage.py migrate --no-input && ./autobets/manage.py runserver_plus 0.0.0.0:8000" expose: - "8000" ports: - "8000:8000" volumes: - ./backend:/app depends_on: - db - rabbitmq restart: on-failure … -
Adding Ajax to Like button not working properly
I am trying to learn more about Ajax and using Like buttons without refreshing the page but I am facing some obstacles trying to figure them out to understand how they work. I am currently getting TemplateDoesNotExist at /blogs/like although it is available, I have messed with it trying to solve it but I need some help knowing what is wrong and how to fix it. The like button was working perfectly without the Ajax but now I am adding it to prevent refreshing so I need some guidance to understand what am I doing wrong Here is the views.py class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment_qs = None comment = Comment.objects.create( post=post, user=self.request.user, content=content) comment.save() return HttpResponseRedirect("blog/post_detail.html") else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form return context def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return … -
Django - Update the final result in views.py every n seconds
I built a stock screener that I want to update the final result based on the latest prices during the market hours. I simplify my original files for better understanding of what I really need. models.py class ScreenerModel(models.Model) pct_choices = [(0, 'all'), (1, 'above 1'), (2, 'below 1')] price_choices = [(0, 'all'), (1, 'above 5000'), (2, 'below 5000')] user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) pct = models.IntegerField(choices=pct_choices, default=0) price = models.IntegerField(choices=price_choices, default=0) urls.py urlpatterns = [ path('users/tmp/<int:pk>/', views.ScreenerModelUser, name='tmp_user'), ] views.py import pandas as pd from .models import ScreenerModel from django.contrib.auth.decorators import login_required from django.shortcuts import render @login_required def ScreenerModelUser(request, pk): user_screener = ScreenerModel.objects.get(user_id=request.user.id, pk=pk) df = pd.read_csv('https://raw.githubusercontent.com/AmirForooghi/stocks_csv/master/stocks_sample.csv') pct_user = user_screener.pct if pct_user == 1: df = df.loc[df.pct > 1] if pct_user == 2: df = df.loc[df.pct < 1] price_user = user_screener.price if price_user == 1: df = df.loc[df.close > 5000] if price_user == 2: df = df.loc[df.close < 5000] context = {'df': df.to_html()} return render(request, 'screener/tmp_user.html', context) tmp_user.html {{ df|safe }} My Problem: As you can see I have online prices in the df and in the views I just filter them according to the user preference. Obviously the prices change during market hours. I want to update the final … -
Two modelformset in one view in django
I'm new to django and I'm trying to have two modelformset in one view but I'm getting the 'ManagementForm data is missing or has been tampered with' error. I have already check the docs and I know that I have to use the management_formset tag and prefix, but I still having the error. I have looked for the answer and I wasn't able to fix the bug. With only one formset all is working as espected. Views.py def soil_page(request): SoilFormSet = modelformset_factory(model=Soil,exclude=False,min_num=1,extra=0) CMCFormSet = modelformset_factory(model=CMC,exclude=False,max_num=1) if request.method == "POST": formset = SoilFormSet(request.POST or None, request.FILES or None, prefix='soils') cmcform = CMCFormSet(request.POST or None,request.FILES or None, prefix='cmcs') if formset.is_valid(): formset.save() if cmcform.is_valid(): cmcform.save() else: formset = SoilFormSet(prefix='soils') cmcform = CMCFormSet(prefix='cmcs') return render(request,'soil/soil_form.html',{'formset':formset, 'cmcform':cmcform,}) HTML <div class="container"> <form id="myform" method="post"> {% csrf_token %} {{ formset.management_form }} {{ formset.as_p }} <input type="submit" value="Save" form='myform'/> </form> </div> <div class="container"> <form id="cmcform" method="post"> {% csrf_token %} {{ cmcform.management_form }} {{ cmcform.as_p }} <input type="submit" value="Save" form='cmcform'/> </form> </div> I hope you can help me. Thanks. -
How to add the heroku nginx buildpack to a python django app with gunicorn?
I am trying to deploy a python with django on heroku and configure an nginx reverse proxy to have like a filter which won't let the requests pass to my django backend until the token is checked to an third party IDP. ** STEP 1 ** I am following this tutorial to add the nginx buildpack : https://elements.heroku.com/buildpacks/hq-mobile/v3-nginx-buildpack After I've added the buildpack and start the app, I get the following message: bin/start-nginx: line 37: bundle: command not found After some digging I noticed some paths need to be added to the config vars for the heroku app in order for bundler to get the needed dependencies : So I've added this paths: heroku config:add GEM_PATH=vendor/bundle/1.9.3 heroku config:set PATH=bin:vendor/bundle/ruby/1.9.3/bin:/usr/local/bin:/usr/bin:/bin Then the config/unicorn.rb file: require 'fileutils' listen '/tmp/nginx.socket' before_fork do |server,worker| FileUtils.touch('/tmp/app-initialized') end Procfile: web: bin/start-nginx bundle exec unicorn -c config/unicorn.rb gunicorn -c gunicorn.conf.py MyApp.wsgi gunicorn.conf.py # gunicorn.conf def when_ready(server): # touch app-initialized when ready open('/tmp/app-initialized', 'w').close() bind = 'unix:///tmp/nginx.socket' workers = 4 Even after adding this, the error still persists. ** STEP 2 ** Once the normal buildpack will be in place I want to follow this tutorial to configure nginx how I want: https://www.nginx.com/blog/validating-oauth-2-0-access-tokens-nginx/ What configuration is needed to … -
How to correctly render the template in class based views? Django translation
I'm working on my Django APP which I give the users the opportunity to choose if they want to see the website in English or Spanish. The problem here is that django is not rendering the correct template. I've tried the "get_template_names" with the language session key, but still dont works... I don`t know if the problem here is the dispatch function. Any help or comments would be helpfull! thank you! views.py class PostListView(LoginRequiredMixin, ListView): model = Post context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def get_template_names(self): language = self.request.session.get(translation.LANGUAGE_SESSION_KEY) if language == 'es': return ['blog/home.html'] else: return ['blog/en_home.html'] def dispatch(self, request, *args, **kwargs): event_change_sets(Post.objects.all()) event_change_sets_co(Post.objects.all()) return super().dispatch(request, *args, **kwargs) The LocaleMiddleware is also activated. settings.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Madrid' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', 'English'), ('es', 'Español') ] -
How to send event to client from any place of server using django channels and websockets
Now I'm building a website using django and angular, And I want to add websocket communication between client and server. I followed the instructions of django channel documentation.( https://channels.readthedocs.io/ ) I want to send any event from any place of django server code. But when multiple users connect via socket, the data sent from server always goes to the last connected user. And here's what I did. First in consumers.py, I defined my ChatConsumer class as follows and added a new handler named "tweet_send" function class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() ... # here's what I added a new tweet send handler async def tweet_send(self, event): content = event['content'] content["group_name"] = self.room_group_name # Send message to WebSocket await self.send(text_data=json.dumps({ "type": "MESSAGE", "data": content })) And somewhere of django server side(in serializers.py), when a new tweet is created, I send a new tweet data to all users using django.channel_layer ... def create(self, validated_data): ... new_tweet.save() # send message via channels channel_layer = get_channel_layer() all_users = list(Member.objects.filter(is_active = True).values_list('id', flat = True)) for user_id in all_users: async_to_sync(channel_layer.group_send)( "chat_{}".format(user_id), # this is the group name … -
multiple model search in django
I want to implement a multi model search in django( search a query from two different models).I have models called location, PropertyFLat and PropertyRoom where location is foreign key in rest of the two models.Now i want to make a search and display result from both PropertyFlat and PropertyRoom models. views.py def search(request): if request.method == 'POST': search_request = request.POST.get('search', False) if search_request: match = PropertyFlat.objects.all().filter( Q(price__istartswith=search_request) | Q(location__state__startswith=search_request) | Q(location__district__startswith=search_request) | Q(location__municipality__startswith=search_request) ) if match: return render(request, 'search_result.html', {'searched': match}) else: match = PropertyFlat.objects.all() error = 'No result found !' return render(request, 'search_result.html', {'error': error, 'error_view': match}) elif search_request == '' or search_request == 'None': return redirect('/') else: price = request.POST.get('price', False) state = request.POST.get('state', False) district = request.POST.get('district', False) if price == '' and state == '' and district == '': return redirect('/') else: match = PropertyFlat.objects.all().filter( Q(price__icontains=price) & Q(location__state__icontains=state) & Q(location__district__icontains=district) ) if match: return render(request, 'search_result.html', {'searched': match}) match = PropertyFlat.objects.all() error = 'No result found !' return render(request, 'search_result.html', {'error': error, 'error_view': match}) return render(request, 'search_result.html') models.py class Location(models.Model): state = models.CharField(max_length=100) district = models.CharField(max_length=100) municipality = models.CharField(max_length=100) ward_no = models.IntegerField() def __str__(self): return "%s %s %s" % (self.state, self.district, self.municipality) class PropertyRoom(models.Model): location = … -
PermissionError at /insert
//Error Page Contents [Errno 13] Permission denied: 'd:/upload/' Request Method: POST Request URL: http://localhost/insert Django Version: 2.1 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'd:/upload/' Exception Location: C:\Users\cocoa\PycharmProjects\myweb\board\views.py in insert, line 27 Python Executable: C:\python study\myweb\Scripts\python.exe Python Version: 3.8.5 //insert content @csrf_exempt def insert(request): frame='' fsize=0 if 'file' in request.FILES: file=request.FILES['file'] fname=file._name with open('%s%s' % (UPLOAD_DIR, frame), 'wb') as fp: for chunk in file.chuncks(): fp.write(chunk) fsize=os.path.getsize(UPLOAD_DIR + fname) row=Board(writer=request.POST['writer'], title=request.POST['title'], content=request.POST['content'], filename=fname, filesize=fsize) row.save() return redirect('/') //views.py Partial Contents row=Board(writer=request.POST['writer'], title=request.POST['title'], content=request.POST['content'], filename=fname, filesize=fsize) row.save() ``` An error occurs when I add a title, name, attachment, and press the confirmation button. What's wrong? Please let me know if you need anything else. I have shallow Python knowledge. I would appreciate it if you could let me know in detail. -
Django template tag if doesn't compare as expected
Django version: $ python -m django --version 3.1.2 My template contains this form: <form method="post"> {% for samtalepartner in elev %} <input type="radio" name="elev" id="elev{{ forloop.counter }}" value="{{ samtalepartner.id }}"> <label for="elev{{ forloop.counter }}"> {{ samtalepartner.id }}{{ request.POST.elev }} {% if samtalepartner.id == request.POST.elev %} <b>{{ samtalepartner.fulde_navn }}</b> {% else %} {{ samtalepartner.fulde_navn }} {% endif %} </label> <br> {% endfor %} <input type="submit" value="Fremhæv valgte"> </form> When I submit first time the browser shows: 1 Andersine Andersen 2 Sida Dida When selecting #2 and submitting again, I expected, as 2==2: 12 Andersine Andersen 22 <b>Sida Dida </b> However, browser shows: 12 Andersine Andersen 22 Sida Dida How come that the two values do not compare and executes the {% if %} statement (rather than the {% else %}? -
Substract a substring from a string in a model object in Django
I'm building a blog website with Django, and for posts on the blog I want to have 2 pages, first page would be the page where all the posts are displayed as a list, and the second would be a page for a specific post, with all the details. On the first page I want to show every post with title, date, and a part of the post's text. I thought that I can add to the post model another field which'll hold a substring from the hole post's text. My post model is this: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) content = models.TextField() display_content = models.TextField(blank=True) tags = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title I want for every post the display_content field to hold the first 167 characters from the content field + "...", and I'm not sure that I'd have to implement something directly on the class Post, maybe a function, or if I need to make this operation on the view function that renders this page with posts. -
NGINX docker-compose - Host not found in upstream nuxt:3000
I'm trying to configure a deployed app on an EC2 instance I'm not able to get visit the application when it's up on ec2 public IP. I've checked the security groups and allowed all inbound traffic to ports just to see If I can reach the homepage or admin page of django. Say my ec2 IP address is 34.245.202.112 how do I map my application so nginx serves The frontend(nuxt) at 34.245.202.112 The backend(django) at 34.245.202.112/admin The API(DRF) at 34.245.202.112/api When I try to do this the error I get from nginx is nginx | 2020-11-14T14:15:35.511973183Z 2020/11/14 14:15:35 [emerg] 1#1: host not found in upstream "nuxt:3000" in /etc/nginx/conf.d/autobets_nginx.conf:9 This is my config docker-compose version: "3.4" services: db: restart: always image: postgres volumes: - pgdata:/var/lib/postgresql/data environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - "5432:5432" expose: - 5432 networks: - random_name django: container_name: django build: context: ./backend env_file: .env environment: - DEBUG=True command: > sh -c "./wait-for-it.sh db:5432 && ./autobets/manage.py collectstatic --no-input && ./autobets/manage.py makemigrations && ./autobets/manage.py migrate --no-input && ./autobets/manage.py runserver_plus 0.0.0.0:8001 " - "8001" volumes: - ./backend:/app depends_on: - db restart: on-failure nginx: image: nginx container_name: nginx ports: - "80:80" restart: always depends_on: - nuxt - django volumes: - ./nginx/conf:/etc/nginx/conf.d - … -
Is safe to open a transaction with raw SQL in Django
With default settings in Django (version 3.1) is safe to do: with connection.cursor() as cursor: cursor.execute("BEGIN") # Some SQL operations commit_or_rollback = "COMMIT" if success else "ROLLBACK" with connection.cursor() as cursor: cursor.execute(commit_or_rollback) Or must I set autocommit to False with set_autocommit method before, as Django's autocommit closes transactions? Or autocommit is isolated and there will be no problem with my code? In case you're asking why I'm using raw SQL for transactions: I've tried using transactions manually as docs indicates but it had some issues with multi-process enviroment, so I had to implement with raw queries -
How to implement third party permissions like DRYPermissions in Django REST framework?
I have user accounts with defined permissions in a permissions column, which contains a string consisting of comma separated permission labels, e.g."create_users,view_users,edit_users,delete_users,". To check whether a user has the permission to perform a specific action it is only necessary to check the permissions of the rows of the user and all groups the user is a member of because whenever a user or customer or any relevance's from user looses permissions, all corresponding users and groups will be updated, i.e. the corresponding permissions will be removed. How can I structure a Viewset in order to assign the mentioned permissions to 'create', 'view', 'edit' and 'delete' actions by the user? I'm trying to do so to have a single function that can be reused for different API endpoints that have the same permission pattern. I think DRYPermissions is a good way to go ahead with, but I am not quite sure on how to implement it or are there any other permission methods which would help me here. Currently I have something like this: class ObjectViewSet(viewsets.ModelViewSet): queryset = ObjectType.objects.all() serializer_class = ObjectTypeSerializer filterset_fields = '__all__' permission_classes = [permissions.IsAuthenticated] class Account(AbstractBaseUser): parent = models.ForeignKey('self', on_delete=models.PROTECT, null=True) name_1 = models.CharField(max_length=255, null=True) password = … -
Updating FilesField() django with S3
I want to update the FileField with new file. All the files are saved on S3. models.py class PrescriptionMediaStorage(S3Boto3Storage): location = settings.AWS_PRESCRIPTION_MEDIA_LOCATION file_overwrite = True custom_domain = f'{settings.AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' class UploadPrescription(models.Model): image = models.FileField(storage=PrescriptionMediaStorage()) For createview i used: prescription_obj = UploadPrescription.objects.create(image=image) prescription_obj.image = prescription_obj.image.url prescription_obj.save() For Updateview i tried this but it's giving error UploadPrescription.objects.filter(id=prescription_id).update(image=image) prescription_obj = UploadPrescription.objects.get(id=prescription_id) prescription_obj.image = prescription_obj.image.url prescription_obj.save() when i tried to open the saved url in image field i got below message <Error> <Code>NoSuchKey</Code> <Message>The specified key does not exist.</Message> <Key>media/prescription/1STUSERS-BANNER.jpg</Key> <RequestId>5D1396D45DF8E1F7</RequestId> <HostId>0Chq0gedgy/o8942zo5JEz2Tp4iE6df51v0o5iY6GnNGKH3bOXb1ee9XKupKY5GYCfvankTGXHI= </HostId> </Error> -
Django application migration
I have a class Tweet, and I am trying to add User model to it such that user can have many tweets, but a tweet only belongs to a user. class Tweet(models.Model): context = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) when I try to migrate i get this error: ValueError: invalid literal for int() with base 10: 'Anonymous' I had a user = models.ForeignKey(User, on_delete=models.CASCADE, default="anonymous") but I removed it and error still presists -
JavaScript is not working in my Django website
I am trying to add auto image slider in my Django website. I referred to this website for the JS and added following code on my setting.py. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["base/templates/"], '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', ], }, }, ] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_DIR = os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' STATICFILES_DIRS = ( [ os.path.join(BASE_DIR, "static"), ] ) My static folder has 2 folders static folder |- css folder - index.css |- js folder - script.js and css works perfectly on web page but JS is not working at all. here is my HTML <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% load static %} <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'css/index.css' %}" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="{% static 'js/script.js' %}"></script> JavaScript code and CSS code are same as in the link above. I would appreciate if you could solve this issue.. -
Authenticate LoginView getting django.utils.datastructures.MultiValueDictKeyError:
Django newbie here I have created a new login form but had troubles with the authentication, read the django documentation and now getting a Multivaluedicktkey error. I am stuck. Initially I have used the build it login view but needed to change it now but things did not go the way I wanted them to be. views.py def login_user(request): form = UserLoginForm(request.POST) email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user is not None: if user.is_active: login(request, user) return redirect('profile') else: form = UserLoginForm() context = { "footer": Footer.objects.filter(name="Generic").first(), 'form': form } return render(request, 'member/register.html', context) forms.py class CustomUserCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': _("Şifreler aynı değil"), } email = forms.EmailField(label="E-Posta Adresi") password1 = forms.CharField(label=_("Şifre"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Tekrar şifre"), widget=forms.PasswordInput, help_text=_("Lütfen aynı şifreyi girin")) class Meta: model = User fields = ['username','email', 'password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError("Vermiş olduğunuz mail adresiyle bir kayıt bulunmaktadır.") return self.cleaned_data['email'] def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserLoginForm(forms.ModelForm): email = forms.EmailField(label="E-Posta Adresi") password = forms.CharField(label=_("Şifre"), widget = forms.PasswordInput) class … -
Set radio button initial value if choices come from queryset
I have a form set up as follows. Form class has radio group: class BookForm(ModelForm): class Meta: widgets = { 'book_type': RadioSelect(attrs={'class': 'horizontal-radiogroup'}), } And in init, the choices are set dynamically: self.fields['book_type'].queryset = available_book_types Where available_book_types is a queryset that is filtered based on conditions. I need to dynamically set a value in the radio group as checked in the template. I tried the following: self.fields['book_type'].initial = available_book_types.filter(category='Fiction').first() But it didn't work. Is there a way to achieve this, or do I need to handle this with JavaScript in the frontend? -
Can't process ajax call on my page because Django request.is_ajax returns True when page is intially loaded
I have a page that makes ajax calls, and my view checks if the call is ajax with .is_ajax function. However, when the page is initially loaded (for example if I stop running the server and then restart it) the is_ajax function seems to return True, which causes a MultiValueDictKeyError at /alltext, because the request does not contain the key "alltext", which contains the data from my other ajax call. The page is a e-commerce product page, and the product has different variants (i.e. size and color), and when the user chooses variants from a dropdown menu (i.e. Large, Blue), it makes an ajax call to the backend to retrieve the price of this specific variant from the database. Here is my code: views.py def product_info(request): if request.method == "GET" and not request.is_ajax: # this is supposed to be loaded on page load return render(request, "product_info.html") elif request.is_ajax and request.method == "GET": print(request.is_ajax) '''When a user chooses a product variant on the page, this makes an ajax call to retrieve the price of this combination''' print("request was ajax") combinations = request.GET["alltext"] combinations_list = combinations.split(";") product = Product.objects.all().latest("id") var_names = Variation.objects.filter(product=product) corresponding_values = [] for i in range(len(combinations_list)): # finding this … -
want to upload image in django without usimg ORM
I want to add upload an image in django. But I don't want to use ORM instead Im using the Mysql commands. But the datatype of images is int in django while blob in mysql what should I do? -
Django-rest-framework How to display links to images from three models
There are 3 django models: Basic model describing the job model: class Homework(models.Model): date_to = models.DateField(auto_now=False) date_created = models.DateTimeField(auto_now=True) lesson = models.CharField(max_length=100) group = models.TextField(max_length=10) body_text = models.TextField(default=None, null=True, blank=True) answer_text = models.TextField(default=None, null=True, blank=True) Job photo model: class Body_Images(models.Model): body_homework = models.ForeignKey(Homework, default=None, on_delete=models.CASCADE) body_image = models.ImageField(upload_to='media/homework/body') And the model of the photo of the answers to the task class Answers_Images(models.Model): answer_homework = models.ForeignKey(Homework, default=None, on_delete=models.CASCADE) answer_image = models.ImageField(upload_to='media/homework/answers') There are also three serializers class GetHomeworkSerializer(serializers.ModelSerializer): body_image = GetHomeworkSerializerBodyImages(many=True) answer_image = GetHomeworkSerializerAnswersImages(many=True) class Meta: model = Homework fields = ('date_to', 'date_created', 'lesson', 'group', 'body_text', 'answer_text', 'body_image', 'answer_image') class GetHomeworkSerializerAnswersImages(serializers.ModelSerializer): answer_homework = serializers.RelatedField(source='Homework', read_only=True) class Meta: model = Answers_Images fields = ('answer_homework', 'answer_image',) class GetHomeworkSerializerBodyImages(serializers.ModelSerializer): body_homework = serializers.RelatedField(source='Homework', read_only=True) class Meta: model = Body_Images fields = ('body_homework', 'body_image') I get an error when trying to get data Got AttributeError when attempting to get a value for field body_image on serializer GetHomeworkSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Homework instance. Original exception text was: 'Homework' object has no attribute 'body_image'. How can I get links to images from Body_Images and Answers_Images in one request? -
How to pass a model instance from one function to the next in Django to prevent hitting the database repeatedly
In the below example you can see that get_object_or_404(Ama, uuid=self.kwargs.get('uuid')) is called three times and hits the database three times. How do I call it only once and pass it around? class InitializeAMAUser(ChoSaaSacLoginRequiredMixin, FormView): template_name = 'components/form.html' def get_form(self, form_class=None): ama = get_object_or_404(Ama, uuid=self.kwargs.get('uuid')) return AmaUserInitializationForm(city=ama.city, request=self.request, email=ama.email, phone = ama.phone, **self.get_form_kwargs()) def get_success_url(self): ama = get_object_or_404(Ama, uuid=self.kwargs.get('uuid')) return ama.get_absolute_url() def form_valid(self, form): form.save() messages.add_message(self.request, messages.SUCCESS, 'User created Successfully') Activity(actor=self.request.user, verb='Initialized Ama User Login') return super().form_valid(form)