Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Want to access a file which is in another docker container from anotherdocker container using python code
We have two docker containers. The first container is backend_device_service which we access using the command -> docker exec -it backend_device_service bash. On this backend_device_container we write our python code. Now I am writing an API which needs to access a file which is on another container rsyslog (server is same just the container is different). We access this container using the command -> docker exec -it rsyslog bash In this container at the path -> /var/log/CPE my file contains which I need to access. However I can access any path in the same container using the following piece of code:- class SysLogReader(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request): content = os.popen('cat /app/sdwan_device_service/devices/views').read().strip('\n').lower() logger.info(f"\ncontent of the file:\n {content}\n") dir_path = os.path.dirname(os.path.realpath(__file__)) resp = {"success":True, "message" : f"Directoty path is {dir_path}"} return Response(resp, status=status.HTTP_200_OK) While my problem is how to access the file which is in another container rsyslog. -
How to add search in the Root pages header in Wagtail admin?
In wagtail admin, there are list of pages and subpages, from the side menu: Pages > Home > How can I add a search field to search for the child pages, as follows? Thanks -
Cart functionality in django
I'm building an ecommerce platform and I want to create the add to cart functionality in the website. But for some reason the quantity is not updating. Here's the views.py: def cart_detail_view(request, product_obj=None): if request.method == 'POST' and request.POST.get('action') == 'create-cart_product': cart_product_form = CartProductForm( request.POST, ) if cart_product_form.is_valid(): try: cart_product_obj = CartProduct.objects.get( product=product_obj, cart__id=request.session.get('cart__id'), ) cart_product_obj.quantity += cart_product_form.cleaned_data.get('quantity') except CartProduct.DoesNotExist: cart_product_obj = cart_product_form.save(commit=False) cart_product_obj.product = product_obj cart_product_obj.cart_id = request.session.get('cart__id') cart_product_obj.save() messages.error(request, 'something is wrong') return redirect('webshop:cart_detail_view') context = { 'cart_product_form': cart_product_form, } return render(request, 'webshop/cart_detail_view.html', context) This is my forms.py file class CartProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CartProductForm, self).__init__(*args, **kwargs) self.fields['quantity'].choices = tuple([(i, i) for i in range(1, 7)]) class Meta: model = CartProduct fields = ( 'quantity', 'product', ) widgets = { 'quantity': forms.Select(), 'product': forms.HiddenInput(), } I need to update quantity in my views but I don't understand how I am gonna do that? -
How to filter django queryset based on the serializer field value?
serializer class MyModelSerializer(serailizers.ModelSerializer): hrs = serializers.SerializerMethodField() get_hrs(self, obj): datetime = SomeModel.objects.filter(id=obj.id).last().datetime now = datetime.now() return (now - datetime).total_seconds() // 3600 class Meta: model = MyModel fields = "__all__" Now in the api there will be a filter paramter hr what it need to do is filter the queryset matching this above calculated hr. For example: @api_view(["GET"]) def get_list(request): qs = MyModel.objects.all() hr = request.GET.get("hr") if hr: qs = qs.filter(hrs=hr) # hrs is not inside model return MyModelSerializer(qs, many=True).data Here hrs is not there inside the Model it's a serializer field above calculated. How can I filter like this from serialzier fields ? Any gudiance would be very helpful. -
Why does changing my render request in views.py break my ability to import images in my base.html?
In my views.py, I have a function for my homepage; @login_required(login_url="/login") def home(request): user_object = User.objects.get(username=request.user.username) user_profile = Profile.objects.get(user=user_object) posts = Post.objects.all() return render(request, "main/home.html", {'user_profile': user_profile}) #This is the problem line and my HTML runs perfectly; <body> <header> <div class="container"> <img src="{% static 'css/images/uReflect.png' %}" alt="logo" class="logo"> <nav> But when I change my home function in views.py to the code below, my page stops working. I have no idea how an error with 'post.image' would correlate to me accessing my images that are independent of posts, and exist in a separate folder. The weirdest part to me is how the error says "NoReverseMatch at /home" but the error doesn't even occur in home.html, it occurs in base.html. Although, home.html does extend base.html; @login_required(login_url="/login") def home(request): user_object = User.objects.get(username=request.user.username) user_profile = Profile.objects.get(user=user_object) posts = Post.objects.all() return render(request, "main/home.html", {'user_profile': user_profile, 'posts': posts}) # Change made here with posts -
Django: query filter
I have two models that are related: one is a list of participants. The other is a list of times they have checked in or out of an office. The table (Checkin) has one record for every checkin/checkout pair. So, there can be many records for any participant. How can I retrieve only the very last (most recent) record for a participants checkin and then pass the participant and only that most recent Checkin record to my template? From what I can tell there's no ability to do something like a last() in my template, so how would I go about filtering to get just that single record? Thank you. Models: class Participant(models.Model): first_name = models.CharField(max_length=50) middle_initial = models.CharField(max_length=50, blank=True) class CheckIn(models.Model): adult = models.ForeignKey( Participant, on_delete=models.CASCADE, blank=True, null=True, related_name='adult_checkin') checkin = models.DateTimeField(blank=True, null=True) checkout = models.DateTimeField(blank=True, null=True) View snipit: p_checkins = Participant.objects.all().order_by('created') queryset = p_checkins context_object_name = "the_list" template_name = 'list_of_checkins.html' -
Is it better to use JsonField or multiple model fields for a Django Model?
For example, class TestModel(models.Model): title = models.CharField(max_length = 200) descriptions = models.JsonField() Or class TestModel(models.Model): title = models.CharField(max_length = 200) description_1 = models.TextField() description_2 = models.TextField() description_3 = models.TextField() description_4 = models.TextField() description_5 = models.TextField() Assume that I have a limited (max 5) number of descriptions. Which approach is better and would be considered as good practice? -
Django server: execute a function once a day
I have a django server which uses a another api to use its resources. In order to use the api, i need to pass access token. And I have refresh token which expires after two weeks. What I want to do is to define a function that checks if refresh token expires that day and if so, update tokens. Most importantly, I want to call that function once a day. I can do that with setInterval in javascript, but what is the most efficient and safest way to implement that feature with python ? -
keep getting bad request when I try to upload image to Django using react native camera
I am trying to make a camera app using react native and send the image to backend using Django. here is the code for taking picture and update it on Django. I tried PUT and POST method. const [image, setImage] = useState(null) const takePicture = async() => { // setimage(null); if(camera){ const options = { base64: true, quality: 0.5 } const data = await camera.takePictureAsync(options) setimage(data.uri); const upload = new FormData(); upload.append('name', '') upload.append('image', image); console.log(upload); fetch("http://192.168.0.154:8000/API/getObjectProperties/object/1/" , { method: 'PUT', // headers: { // 'Content-Type': 'application/json' // }, body: upload } ).then( (res) => res.json()).catch( (error) => console.error(error)); } } const takePicture = async() => { // setimage(null); if(camera){ const options = { base64: true, quality: 0.5 } const data = await camera.takePictureAsync(options) setimage(data.uri); const upload = new FormData(); upload.append('name', '') upload.append('image', image); console.log(upload); fetch("http://192.168.0.154:8000/API/getObjectProperties/object/1/" , { method: 'PUT', // headers: { // 'Content-Type': 'application/json' // }, body: upload } ).then( (res) => res.json()).catch( (error) => console.error(error)); } } but I keep getting bad request although it works when using postman. bad request the FormData is it because it cannot read the file from the camera.takePictureAsync() as it is like "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FThesisApp-1fe17b3a-01c2-46c4-953e-6368f5dc1eeb/Camera/d909cdfe-9d40-4788-a212-63780d715321.jpg" instead of just d909cdfe-9d40-4788-a212-63780d715321.jpg? is there any solution … -
Unable to display string from backend to Django Template
Hi I am unable to display some string from my custom view backend to django template. The string from backend is able to send over to the client side browser but still unable to display. The error message that I am trying to display is a lockout message from django-axes. it is a custom view function that returns a HttpResponse(JsonResponse(response_data)) where the response_data is as shown in the image inserted. Below is what I have tried. HTML <div class="login-form clrbg-before"> <p class="text-success" id="login-success" style="display: none;"></p> <form role="agent-login" class="login" id="" action="{% url 'agent-login' %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" placeholder="Email address" name="email" class="form-control"> </div> <div class="form-group togglepassword-right"> <input type="password" placeholder="Password" name="password" class="form-control"> <i class="glyphicon glyphicon-eye-open form-control-feedback" id="togglePassword"></i> </div> <p class="text-danger text-center" id="password-error" style="display:none;"> {{ errors }}</p> <div class="form-group"> <button data-request="ajax-submit" data-target="[role='agent-login']" class="btn-1 " type="button"> Login now </button> </div> </form> <div style="text-align: center;"> <a href="#" class="gray-clr" id="agent-forgot"> Forgot Password? </a> </div> </div> views.py def agent_login(request): start = time.time() sop(start) response_data = {'login': "Failed"} redirect_url = '' data = [] error = False errors = {} result = 'FAIL' message = '' response_status = HTTP_400_BAD_REQUEST if request.POST: redirect_url = '' data = [] error = False errors = {} result … -
Django deploy on App Engine raise error: connection to server at "127.0.0.1", port 5432 failed:
i am trying to deploy my django web app on Google Cloud App Engine, but are running to a connection error. This is after I have done all the configuration like main.py, entry point, app.yaml. After doing some digging, they all point to my postgresql database blocking my connections somehow, but i checked and my database is up and running on sql cloud. Here is the screenshot of the error: [the error image][1]: https://i.stack.imgur.com/bDIfY.png Here is my app.yaml file: # [START django_app] runtime: python38 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: django_blog.wsgi.application env_variables: APPENGINE_URL: https://engineblog.wn.r.appspot.com #entrypoint: gunicorn -b :$PORT django_project.wsgi:main inbound_services: - warmup # Only pure Python libraries can be vendored # Python libraries that use C extensions can # only be included if they are part of the App Engine SDK # Using Third Party Libraries: https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27 # libraries: # … -
Django - User Password Change by coding
I am trying to give permission to change password for logged in user. coded as below.. result comes as password has been changed but password not set. def changepassword(request): if request.method == 'POST': user = authenticate(request, username=request.user,password=request.POST['old']) if user is None: return render(request, 'pmp/changepassword.html', {'error': 'Current Password Enter Mismatch! '}) else: try: if request.POST['password'] == request.POST['confirm']: u = request.user u.set_password('password') return render(request, 'pmp/changepassword.html', {'success':'Password has been changed!'}) else: return render(request, 'pmp/changepassword.html',{'form': AuthenticationForm(), 'error': 'New Password and confirm Password mismatch!'}) except ValueError: return render(request, 'pmp/changepassword.html',{'form': AuthenticationForm(), 'error': 'Password not changed!'}) return render(request, 'pmp/changepassword.html') -
How to fix `TypeError: 'AnonymousUser' object is not iterable ` in Django
I'm using LoginRequiredMixin in Django. However I got error. TypeError: 'AnonymousUser' object is not iterable It happen in this line if Speaker.objects.filter(user=self.request.user, is_deleted=False).count() == 0: of this code. class SpeakerListView(LoginRequiredMixin, ListView): template_name = 'speaker/list.html' context_object_name = 'speakers' model = Speaker def dispatch(self, request, *args, **kwargs): # if user does not have speaker, redirect to create view if Speaker.objects.filter(user=self.request.user, is_deleted=False).count() == 0: messages.error(request, _('xxx')) return redirect('speech:speaker_add') return super().dispatch(request, *args, **kwargs) If you know, how to solve this problem. Please help me! -
Django: Update 2 tables
I'm trying to update two tables/models at once, but I'm stumbling on the correct approach. I have two models: Models (a simplified representation) : class WaiverAdult(models.Model): first_name = models.CharField(max_length=50, blank=True) class CheckIn(models.Model): adult = models.ForeignKey( WaiverAdult, on_delete=models.CASCADE, blank=True, null=True, related_name='adult_checkin') checkintime = models.DateTimeField(blank=True, null=True) checkoutime = models.DateTimeField(blank=True, null=True) Here is my view: def checkin(request): waiver_id = request.POST.get('id') action = request.POST.get('action') if waiver_id and action: try: adult = WaiverAdult.objects.get(id=waiver_id) if action == 'checkmein': c = CheckIn(adult=adult) c.save() adult.status = True adult.save() ... I'd like to also save the "checkintime" to Checkin. Any direction is greatly appreciated. Thank you. -
Can't import module NAME - django password validators
I am trying to add custom password validators in Django but i can't figure out why it wouldn't import the module. Anyone has encountered this issue or can tell me why i have this error please ? Here is the code in authentication/validators.py: from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ class LowercaseValidator(object): def validate(self, password, user=None): if not re.findall('[a-z]', password): raise ValidationError( _("The password must contain at least 1 lowercase letter, a-z."), code='password_no_lower', ) def get_help_text(self): return _( "Your password must contain at least 1 lowercase letter, a-z." ) Here is my updated settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 12, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, { 'NAME': 'authentication.validators.LowercaseValidator', }, ] And here is the error i have: The module in NAME could not be imported: authentication.validators.LowercaseValidator. Check your AUTH_PASSWORD_VALIDATORS setting. P.S: i did create an app called "authentication" and my validators.py is in the folder of the application. Thank you in advance for your answers ! -
Django: images not loading instead of alternative text
I tried to display media thumbnails from other news website on my django website homepage by using feedparser, but the image is not loading, instead the alternative displayed: this is my current homepage looks like homepage.html: <div class="col-md-2 my-auto"> <img src="{{ post.image.url }}" class="img-fluid ml-3 my-3" alt="{{ post.pubdate }}" > </div> models.py: class Post(models.Model): title = models.CharField(max_length=200) description = models.TextField() pubdate = models.DateTimeField() link = models.URLField() image = models.URLField() def __str__(self): return self.title startjobs.py(this file used feedparser to parse news): logger = logging.getLogger(__name__) def save_new_posts(feed): feed_title = feed.channel.title feed_image = feed.channel.image['href'][0] for item in feed.entries: if not Post.objects.filter(link=item.link).exists(): post = Post( title=item.title, description=item.description, pubdate=parser.parse(item.published), link=item.link, image=feed_image, ) post.save() def fetch_realpython_posts(): _feed = feedparser.parse("http://feeds.foxnews.com/foxnews/latest") save_new_posts(_feed) def fetch_talkpython_posts(): _feed = feedparser.parse("https://feeds.nbcnews.com/nbcnews/public/news") save_new_posts(_feed) def delete_old_job_executions(max_age=604_800): DjangoJobExecution.objects.delete_old_job_executions(max_age) views.py: class HomePage(ListView): template_name = "homepage.html" model = Post paginate_by = 10 ordering = ['pubdate'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["posts"] = Post.objects.filter().order_by("-pubdate")[ :10 ] return context main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path("", include("news.urls")), path('accounts/', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='homepage.html'), name='homepage'), ] Not sure why the image is not displayed instead of alternative text, any help would be appreciated -
How can I get ip address in django
I am building an application in Django that gets the ip address of the user to track their location. And once their location is determined, I want to be able to figure if their signup date coincides with a holiday in their country. Please, how can I do this? Any module or library to install? Do I have to include some details in the models? Thanks. -
connect `sqlachemy` to the django db
Is there a way to connect sqlalchemy to the django db? I am running a django test where a test database is created connection._connections.settings['default'] gives: {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test_db', 'USER': 'postgres', 'PASSWORD': 'qwertyu', 'HOST': 'localhost', 'PORT': '5432', 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}} But if I try to connect to this database using sqlalchemy: user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] database_url = 'postgresql+psycopg2://{user}:{password}@localhost:5432/{database_name}'.format( user=user, password=password, database_name=database_name, ) engine = create_engine(database_url, echo=False) a completely new database is created. So any data inserted using model.bulkcreate() live is a different database than the one created by sqlalchemy. I would like to be able to use both. I want to use sqlalchemy for long time series (1M to 10M rows) where model.bulkcreate() is taking very long. I find it weird that the engine of connection is 'django.db.backends.postgresql', while the engine of sqlalchemy is postgresql+psycopg2 or postgresql. Is there a way to connect connection with sqlalchemy? thanks -
How to make Apache pass through basic auth to Django?
How do you configure Apache to pass through all basic authentication requests so that they're handled by a Django WSGI site Apache's hosting? I've implemented a basic authentication handler directly in Django, based on this snippet, so that it integrates easily with the built-in admin app, and is more easy to unittest and integrate with my Django application's custom logging. This works perfectly when run from the devserver. Unfortunately, I'm finding that when run from behind Apache, the default Apache config denies all basic authentication requests, and doesn't bother to send them to Django. These docs recommend some ways to setup conventional Apache basic auth configs, but they all assume a hard-coded path and special permissions for this distinct site, which has to be setup to explicitly do the credential checking with data passed from Apache. I have application logic that dynamically determines the paths that should be tested for basic auth, and therefore need to be handled by Django, and never by Apache so I don't want Apache to do anything for basic authentication. I just want it to pass through the request, and let Django worry about checking credentials, and then returning a 401 response. I can't find … -
How to extract text from a word doc textbox using Python/Django and docx
I am trying to extract and replace text in a .docx word file using the docx library with python (3.7) which i then save as "TESTFIL.docx" The normal paragraph text in the doc extracts fine and i can replace it, however any text within a textbox is not being picked up. Appreciate any help, tips or libraries i can use side note: the Aspose library does both, but the $1000 license fee is just too much for this project. Code snippet below: def replaceDoc2(self,file,variables): print("WE Here") doc=Document(file) Dictionary = {"NAME": "SHILLAN", "MEMBERSHIPNO":"0007"} for i in Dictionary: for p in doc.paragraphs: print(p.text) if p.text.find(i)>=0: p.text=p.text.replace(i,Dictionary[i]) #save changed document if os.path.exists("TESTFIL.docx"): os.remove("TESTFIL.docx") doc.save('TESTFIL.docx') else: print("The file does not exist") doc.save('TESTFIL.docx') -
How to select a specific HTML element from a for loop in a Django template?
I am trying to create a button that hides and displays only the specific HTML elements that are in the same div with it through JavaScript. All the divs are within a Django template for loop and display different information. Right now, I am using a querySelector to select the id, but that is not correct because it selects the first element it finds with that id. html <div> {% for post in page_obj.object_list %} <div class = "individual_posts"> <a href="{% url 'username' post.user %}"><h5 id="p_user" class = "post_user">{{ post.user }}</h5></a> <h6 id = "post_itself">{{ post.post }}</h6> <h6 id="date_and_time" class = "post_elements">{{ post.date_and_time }}</h6> <h6 id="likes" class = "post_elements">{{ post.likes }}&#x1F44D;</h6> {% if post.user == request.user %} <button class="edit_button" value="{{ post.id }}">Edit</button> {% endif %} <textarea class="textarea" id="edit_area"></textarea> <input type="submit" value="Save" class="edit_save" id="save"> </div> {% endfor %} </div> javascript document.addEventListener('DOMContentLoaded', function(){ //hide the textarea const editingTextareas = document.querySelectorAll(".textarea"); for (const textarea of editingTextareas){ textarea.style.display = 'none'; } //hide the save buttons for the textarea const saveButtons = document.querySelectorAll(".edit_save"); for (const s_button of saveButtons){ s_button.style.display = 'none'; } //adds the click to the edit buttons const editButtons = document.querySelectorAll('.edit_button'); for (const button of editButtons) { id = button.value; button.addEventListener('click', () => … -
Where to find the headers of its deployed heroku application?
This is a pretty short question. I deployed a Django app to heroku and would like to have access to the contents of that app's security headers. The subject is not well documented on the Internet. I don't know the procedure to access it. Thanks! -
how to load image from django models
i want to load the picture from model. but i get "<QuerySet [<Photo: ira>]>" except of photo. i have tried to use photo.url, photo.image.url, photo.image, photo.image.image but it does not work my templtate: <div id="userInfo"> <img src="{{ photo.url }}" alt="{{ username }}"> <div id="statusAndName"> <h1>{{ username }}</h1> <h3>{{ status }}</h3> </div> </div> my view: def UserPage(request,user_num): user = User.objects.get(pk=user_num) #get user info username = user.username posts = Post.objects.filter(user=user.id) photo = Photo.objects.filter(user=user.id) status = user.status return render( request, 'userpage.html', context={'username': username, 'posts': posts, 'status': status, 'photo': photo}, ) my models: class Photo(models.Model): """ A typical class defining a model, derived from the Model class. """ # Fields user = models.OneToOneField('User', on_delete=models.SET_NULL, null=True, help_text="user's id") photo = models.ImageField() # Metadata class Meta: ordering = ["-user"] def __str__(self): """ String for representing the MyModelName object (in Admin site etc.) """ return self.user.username -
Why do I get this error when I deploy a Django App in Railway?
There is a problem when I deploy a Django app in Railway, this is the error that is in the logs. Error message I have looked up the error in Google, and I got that I have to change the library "psycopg2" to "psycopg2-binary", but I still get the same error. Version of psycopg2-binary Is there some idea about what is happening? -
How to access the filtered list of related objects when using FilteredRelation?
I have a list of Funds that I have to query by their related model Commitment (as in "return the funds in which associated commitments fill this criteria). I need to annotate each fund with an aggregation over the filtered commitments, as well as access each item in the filtered relation. I'm trying to use FilteredRelation: funds = Fund.objects.annotate( f_commitments=FilteredRelation( "commitments", condition=Q(pk="c40ae23d-50ee-47c5-9397-c1670098ecd9") ) ) I'm trying a basic query just to test the filter. The query runs, but the funds it returns don't have a f_commitments attribute as it usually does with annotations: AttributeError: 'Fund' object has no attribute 'f_commitments' Is there something wrong with the query or FilteredRelation don't support accessing the filtered items directly?