Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django object cache with memcache after pickling
I was trying to cache a Django model Instance like class MyModel(models.Model): ... several atributes, as well as foreign key attributes ... from pymemcache.client import base import pickle obj = MyModel.objects.first() client = base.Client(("my-cache.pnpnqe.0001.usw2.cache.amazonaws.com", 11211)) client.set("my-key", pickle.dumps(obj), 1000) # 1000 seconds # and to access I use obj = pickle.loads(client.get("my-key")) They both works fine, but sometimes executing the same line: client.get("my-key") generates very very strange errors.(different errors like KeyError, OSError) like Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 823, in _fetch_cmd prefixed_keys) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 791, in _extract_value key = remapped_keys[key] KeyError: b'some-other-cache-key' and sometimes I get: Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 833, in _fetch_cmd raise MemcacheUnknownError(line[:32]) and sometimes, I get Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 823, in _fetch_cmd prefixed_keys) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 790, in _extract_value buf, value = _readvalue(self.sock, buf, int(size)) File … -
Django: is there an assertNumQueries method which can run the assertion as a subtest?
I'd like to run a block of code and ensure the amount of queries generated is in check, however, I want the test code to proceed if this check fails. Pseudo-code: def assertNumQueriesSubTest(func, expected_number): with self.countNumQueries as query_count: func() with self.subTest('query check'): self.assertEqual(queries_count, expected_number) With the classic assertNumQueries, the test code stops if the query count does not match the expected value, however, this prevents me from debugging tests properly, since the reason for which the query count changed may not be obvious, so I would like to know if at least the behavior matches is still the same or not. -
NoRevereMatch for named URL with keyword arguments
Error shown: Reverse for 'post_detail' with keyword arguments '{'username': 'admin', 'group_name':'laravel', 'pk': ''}' not found. 1 pattern(s) tried: ['users/(?P<username>[^/]+)/groups/(?P<group_name>[-a-zA-Z0-9_]+)/posts/(?P<pk>[0-9]+)/general/$'] group_list.html This is a generic ListView template. ... {% for group in object_list %} {% with group.post_set.all|first as post %} <a href="{% url 'post_detail' username=user.username group_name=group.name_slug pk=post.pk %}">{{ group.name }}</a> {% endwith %} {% endfor %} ... Main issue: In the template file, all three of the arguments are displayed correctly i.e. {{ user.username }} {{ group.name_slug }} {{ post.pk }}. But, if they are passed in as keyword argument in the named URL, one of the three is empty, and other two correctly passed. Note: There is no space between individual URL keyword arguments. -
django form not working when manually rendering form fields
I have a django form that I was rendering with {{ form | crispy}} for front end purposes I need to render the form fields manually. When rendering the fields manually the form does not submit. It works perfectly if I use the {{ form | crispy}}. The only change i made to the code is in the html rendering the elements manually html <div class="content-section"> <form method="post" enctype="multipart/form-data" id="PostForm" data-models-url="{% url 'ajax' %}" novalidate> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Post</legend> {{ form.image | as_crispy_field}} <h4>heading text</h4> <hr class="solid"> {{ form.title | as_crispy_field}} <h4>Heading text</h4> <hr class="solid"> {{ form.model | as_crispy_field}} <h4>Heading text</h4> <hr class="solid"> {{ form.manufacture | as_crispy_field}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def save(self, *args, **kwargs): super(Post,self).save(*args, **kwargs) forms.py from crispy_forms.layout import Fieldset, Layout from django.forms import ModelForm from blog.models import Post, Manufactures, Models from crispy_forms.helper import FormHelper class PostForm(ModelForm): class Meta: model = Post fields = 'image', 'title', 'model', 'manufacture' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['model'].queryset = Models.objects.none() if 'manufacture' in self.data: try: model_manufacture_id = int(self.data.get('manufacture')) self.fields['model'].queryset = Models.objects.filter(model_manufacture_id=model_manufacture_id)#.order_by('name') except (ValueError, … -
Redirect user to different page after successful login attempt
I'm making a simple CRUD app and learning how to handle making user accounts and logging in. When a user successfully logs in, I'd like him to be redirected to a certain page (for example, BASE_URL + '/notebooks'). What would be the best way to go about this? I'm stumped as to how exactly to go about this. I was thinking of using react-router-dom's useHistory() hook and just doing history.push() on the handleSubmit function, but then how would I return the response data to the form? Should I try to go about this using the backend? Here's my login form: export function Login() { const [ email, setEmail ] = useState('') const [ password, setPassword ] = useState('') async function handleSubmit(e) { e.preventDefault() try { const response = await axiosInstance.post( '/auth/token/obtain/', { email, password } ) axiosInstance.defaults.headers['Authorization'] = 'JWT ' + response.data.access localStorage.setItem('access_token', response.data.access) localStorage.setItem('refresh_token', response.data.refresh) return response.data; } catch(err) { throw err; } } return ( <div> <div> <div> <div> <div> <p> Log in </p> </div> <div> <form onSubmit={handleSubmit}> <ol> <li> <input name='email' value={email} placeholder='Email address' onChange={e => setEmail(e.target.value)} /> </li> <li> <input name='password' type='password' value={password} placeholder='Password' onChange={e => setPassword(e.target.value)} /> </li> <li> <input type='submit' value='Submit' /> </li> </ol> … -
Django log login attemps and after 3 failed attemps lock out user
So i am pretty new to Django. Actually my first project. I want to create a custom model "Logging" in which i want to log the admin login attempts and count the attempts. After 3 failed login attempts the user must me locked out. So how can i log custom admin attempts? -
some CSS is not working after adding "extends/base,html"
I am building a toggle button and i am using some CSS but when i try to run code then one CSS command is not working. When i remove {% extends 'base.html' %} then it works perfectly but after adding it doesn't load a function. toggle.html .menu-item, .menu-open-button { background: #EEEEEE; border-radius: 100%; width: 80px; height: 80px; margin-left: -35px; margin-top: 230px; position: absolute; color: #FFFFFF; text-align: center; line-height: 100px; -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); -webkit-transition: -webkit-transform ease-out 200ms; transition: -webkit-transform ease-out 200ms; transition: transform ease-out 200ms; transition: transform ease-out 200ms, -webkit-transform ease-out 200ms; } line-height: 100px; is not working after adding extends base.html which is necessary. I have searched everywhere AND i have also tried by deleting every element on base.html then i notice that after deleting every single link it is working. Any help would be much Appreciated. Thank You in Advance. -
Is there a better solution instead of ModelMultipleChoiceField?
I have a form where users can create a fishing trip and they can add multiple participants from the registered users (fishermen). models.py class Fisherman(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fisherman_id = models.AutoField(primary_key=True) class Meta: verbose_name = "Fisherman" verbose_name_plural = "Fishermen" def __str__(self): return f'{self.user.username}' class Trips(models.Model): lake = models.CharField("Lake", max_length=150) city = models.CharField("City", max_length=100, blank=True) s_date = models.DateTimeField("Starting Date", auto_now=False, auto_now_add=False) e_date = models.DateTimeField("Ending Date", auto_now=False, auto_now_add=False) fisherman = models.ManyToManyField(Fisherman) trip_id = models.AutoField(primary_key=True) total_catch_weight = models.DecimalField(max_digits=5, decimal_places=2, default=0) class Meta: verbose_name = "Trip" verbose_name_plural = "Trips" def __str__(self): return f"{self.lake} - {self.trip_id}" forms.py class TripsForm(forms.ModelForm): fisherman = forms.ModelMultipleChoiceField(queryset=Fisherman.objects.all().exclude(user__username="admin"), widget=forms.SelectMultiple(attrs={'class': 'form-select'})) class Meta: model = Trips fields = ["lake", "city", "s_date", "e_date", "fisherman"] widgets = { "lake": forms.TextInput(attrs={'type': 'text', 'class': 'form-control', 'id': 'LakeInput',}), "city": forms.TextInput(attrs={'type': 'text', 'class': 'form-control', 'id': 'CityInput',}), "s_date": forms.DateTimeInput(format='%Y-%m-%d %H:%M', attrs={'class':'datetimefield form-control', 'id': 'StartingDate',}), "e_date": forms.DateTimeInput(format='%Y-%m-%d %H:%M', attrs={'class':'datetimefield form-control', 'id': 'EndingDate',}), } I'm currently using ModelMultipleChoiceField that lists all existing fishermen in the form, but I would like to find a better solution because I don't want that users could see all registered fishermen. Is there a way to add more fishermen to the trip by typing their names? Is it possible in case of manytomanyfield? I don't … -
how to show Html Div after Ajax Success in Django
i have Djnago App and i want message appear to the user after Ajax call Successs here is y Messages html <a id="added" class="btn btn-template-outlined" href="{% url 'shop:add_product' id=products.id %}">Add to cart</a> <p id="connt" class="text-center"> {% if messages %} {% for message in messages %} {{message}} {% endfor %} {% endif %} </p> and here is my Ajax $("#added").click(function(e){ e.preventDefault(); $.ajax({url: "{% url 'shop:add_product' id=products.id %}", success: function(response){ appendToUsrTable(); }}); }); function appendToUsrTable() { ("#connt").append(` `) } </script> -
While Running GraphQL mutaion I am constantly getting this error
#unknown argument on field of type mutation #simple query I am running even after changing the input name it is throwing syntax error Can you please suggest mutation { createUnapprovedPart(Input:{part:"1234"}) { part {id} changeset { id creationDate effectiveDate } } If I change the name I am getting like syntax error -
Confusion about django
I am new to web development. I have already learned basic HTML, CSS and javascript. I want to use django as a backend. And I am aware of frontend framework like REACT. I want to use mongo db database and REACT framework along with Django. Can I do so or not. I mean can i integerate all these things to make a web application and if so what are advantages or disadvantages or should I go for MERN. -
How i can compare string if it has both quotation marks and apostrophes?
I want to check in my x.html file if value of string string has specific text - this text is aaaa"'b' and 'c'"aaaa So it has both, quotation marks and apostrophe. In this case when i do this {% if string == "aaaa"'b' and 'c'"aaaa" %} do something {% endif %} this is not working. How i can cope with that? -
Cannot assign "2": "Card.set" must be a "Set" instance
I am currently making a flashcard web application with Django. There is a 'set' page (dashboard) and a 'card' page (set-edit). When I fill in and submit the form on the card page (set-edit) to add a new card to the set which has been selected for editing, I receive a value error 'Cannot assign "2": "Card.set" must be a "Set" instance.' I'm unsure why this is happening because there is an instance of Set with an id of 2. Any suggestions of how to rectify this issue? views.py ################### ##Dashboard views## ################### def dashboard(request): set = Set.objects.all() set_count = set.count() if request.method == 'POST': form = SetForm(request.POST) if form.is_valid(): form.save() set_name = form.cleaned_data.get('name') messages.success(request, f'{set_name} has been added') return redirect('dashboard-dashboard') else: form = SetForm() context = { 'set': set, 'form': form, } return render(request, 'dashboard/dashboard.html', context) ############# ##Set views## ############# #Cards is for when you are adding cards to a set or looking at the content of a set def set_edit(request, pk): set_title = Set.objects.get(id=pk) card = Set.objects.get(id=pk).card_set.all() set_id = pk set = Set.objects.get(id=pk) if request.method == 'POST': form = CardForm(request.POST) print('Entered Post condition') if form.is_valid(): obj = form.save(commit=False) obj.set = pk obj.save() card_name = form.cleaned_data.get('kanji') messages.success(request, f'{card_name} has … -
I am working on DjangoRest project whenever i try to execute command python manage.py runserver or python manage.py shell It won't work
This is my settings.py file and I've created a .env file which contains secret key and other stuffs. I tried installing reinstalling python changing path deleting and again adding project and even I reinstalled vs code but it won't work i dont know where's the problem. This command python manage.py runserver or python manage.py shell or any other related commmand won't work """Settings.py""" """ Django settings for doorstepdelhi project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from decouple import config import django_heroku import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config("DEBUG", default=False, cast=bool) ALLOWED_HOSTS = ["localhost", "127.0.0.1"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', "versatileimagefield", "nested_admin", 'drf_yasg', "django_extensions", 'channels', "accounts", "webtraffic", "store", "product", "shop", "wishlist", "payment", 'core', … -
Login with google
Several social services will not allow redirecting users to 127.0.0.1 or localhost after a successful authentication; they expect a domain name. In order to make social authentication work, you will need a domain. ............................................................................................. If you are using Windows, your hosts file is located at C:\Windows\System32\Drivers\etc\hosts. To fix this edit your /etc/hosts file and add the following line to it: 127.0.0.1 mysite.com .............................................................................................. So, the problem is that it returns "mysite.com refused to connect." -
How do I have child divs automatically position restrained within a parent div?
I have the following CSS for a div box within a larger page container div: .mybox{ position: relative; width:20%; max-height: 100%; min-height: 25%; } I want to be able to add multiple of these dynamically using a django for loop, so I want them to space themselves out automatically while still remaining inside the parent div. This is because I can't set position values on each item if they are created at runtime. Anyone know how I can do this? -
Python - Django The submit button does not work when I submit a form
I'am developing a website in Python Django. I want to code a form which send me by email the email address that the users put in the form. The problem is that the submit button does not work. When I click the button submit, I am not redirected to a new page and I am not receiving the content of the form. Can you help me to fix it ? My views def test(request): if request.method == 'GET': form = newsletterForm() else: form = newsletterForm(request.POST) if form.is_valid(): subject = 'New Subscriber' from_email = 'no-reply@test.com' message = ' Email Adress: ' + form.cleaned_data['from_email'] try: send_mail(subject, message, from_email, ['info@test.com']) messages.success(request, 'Thank you for contact us we will get back soon') render(request, "Test.html") except BadHeaderError: return HttpResponse('Invalid header found.') render(request, "Test.html") return render(request, "Test.html", {'form': form}) My HTML <form id="newsletterForm" class="contact-form" action="#" method="post"> <div class="input-group input-group-rounded"> {{ form.from_email|add_class:"form-control" }} <span class="input-group-append"> <button class="btn btn-light text-color-dark" type="submit"><strong>GO!</strong></button> </span> </div> </form> My forms class newsletterForm(forms.Form): from_email = forms.EmailField(label='search', widget=forms.TextInput(attrs={'placeholder': 'Email Address'})) -
Image saving in Database using Django giving Error "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
Hi I am extracting frames from video and want to store these frames into database using Django. Here is my code : def saveFrame(request): video = Video.objects.last() path = os.path.dirname(__file__) path = path.replace('videos',video.video.url) clip = VideoFileClip(path) clip = clip.subclip(0, 15) clip = clip.cutout(3, 10) clip.ipython_display(width = 360) cap= cv2.VideoCapture('__temp__.mp4') i=0 image = Image() while(cap.isOpened()): ret, frame = cap.read() if ret == False: break image.video_id = video image.title = video.title +str(i) image.imagefile = frame image.save() print(i) i+=1 cap.release() cv2.destroyAllWindows() When i run this code i recieve this error : Error in image.save() ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Can anyone help me with this issue so I can save images into database. -
How to get list of the Postgres databases on Google Cloud using Django/Python
I intend to get the list of databases that are available PostGreSQL instance on Google Cloud. With command line gcloud tool the following provides the expected result for my project : gcloud sql databases list --instance=mysqlinstance How can I get the same result through python / django while using google cloud ? -
SyntaxError: expression cannot contain assignment, perhaps you meant "=="? in django [duplicate]
I am facing one issue dimension = ['category','amount'] // Just imaging I am getting an array like this frim request for _, obj in enumerate(qs1): kwargs.update({obj[dimensions[1]]: Count(dimensions[1], filter=Q(dimensions[1]=obj[dimensions[1]]))}) Here I'm getting an error like this SyntaxError: expression cannot contain assignment, perhaps you meant "=="? in django If I am changing my code like this it will work , but my issue is that I am using filtering option there so I need to get the exact field name that user passed in the dimensions dimension = ['category','amount'] // Just imaging I am getting an array like this frim request for _, obj in enumerate(qs1): kwargs.update({obj[dimensions[1]]: Count(dimensions[1], filter=Q(filter_data =obj[dimensions[1]]))}) I -
error: Someip:port is not a valid port number or address:port pair
This is the first time I am deploying a django application. I created an AWS ec2 ubuntu instance. I followed the steps in this tutorial- https://adeshg7.medium.com/deploy-django-postgresql-on-ec2-using-apache2-from-scratch-42dc8e6682c1 The demo project was running fine on the server http://MyPublicIPv4Address:443. I then added another port in the security groups in AWS, and after that whenever I run "python manage.py runserver http://MyPublicIPv4Address:443 " on the puTTY connection command line, it gives me the same error: CommandError: "http://MyPublicIPv4Address:443" is not a valid port number or address:port pair. This seems like a django error in a very old version: https://code.djangoproject.com/ticket/14928. I cant find a way around this error. Any help would be appreciated. Thankyou -
Heroku logs drain (stream) guidance
I have a simple Django webApp, which involve several workers as well, running related jobs. I would like to stream Heroku logs into the webApp for a dashboard view, so that users could track the workers progress within the webApp. I'm not sure how to access the logs from the Django view (then pushing the content back to the Ajax caller). As far as I know, the Heroku logs can be retrieved by either Heroku UI, Heroku CLI or Heroku Log-Drain (or by some 3rd party add-ons). I think that Heroku Log Drains, with Logplex, could address this feature, but I'm not sure how to technically achieve that behavior. Which steps shall be taken for achieving the desired behavior, as described above? -
"Error: Error decoding signature" and "Variable '$token' is never used in operation 'VerifyToken'."
Tools: Django + Next.js + Django-GraphQL-JWT What works: I can login the user and obtain a JWT token, which I save in addition to saving the token in the localStorage to retrieve and verify later. What does not work: I can successfully retrieve the localStorage token, but when I try to use the library to verify the token on the server, I get this error: [GraphQL error]: Message: Error decoding signature, Location: [object Object], Path: verifyToken Verification code: const [authToken, setAuthToken] = useState(null); const [localToken, setLocalToken] = useState(); useEffect(() => { setLocalToken(localStorage.getItem("token")); }, []); ... const verifyToken = async () => { const client = createApolloClient(); const data = await client.mutate({ mutation: verifyMutation, variables: { token: localToken }, }); if (data) { setAuthToken(data.data.tokenAuth.token); } return data; }; ... Mutation: export const verifyMutation = gql` mutation VerifyToken($token: String!) { verifyToken(token: $token) { payload } } `; schema.py: class Mutation(graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() revoke_token = graphql_jwt.Revoke.Field() Here is what happens when I try this manually in GraphQL: If my mutation includes the token: mutation VerifyToken($token: String!) { verifyToken(token: "token_string_here") { payload } } returns: { "errors": [ { "message": "Variable '$token' is never used in operation … -
Django emails with a name over 75 characters
how are you? I am having trouble sending emails because of the sanitize_address() Django function. There is a ticket who talks about this: https://code.djangoproject.com/ticket/31784 The problem is: In the process of sending an email the addresses is sanatized: django/core/mail/message.py:98 => def sanitize_address(addr, encoding) The Name portion is encoded via the Header class email.header.Header.encode which will introduce newlines at 75 characters. Essentially Django seems to no longer accept send emails with names longer than 75 characters. How can I send emails with a name over 75 characters? There is a way to do it? Thank you in advance. Regards. -
Directly setting http only cookie in browser from django (frontend is svelte)
I am trying to send a http-only cookie from django response to svelte. The cookie reaches svelte using fetch, but it doesn't come into the browser. Is there a way to set cookie from django directly in the browser? Without using svelte? If no, then how to set an http-only cookie using svelte. Any help is much appreciated!!!