Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Type Error Matching query does not exist
Currently experiencing something very strange. Though, I've got a plain-vanilla function & template, I receive a TypeError that refers to a line in my views.py belonging to a different function / template... views.py: def shopping(request): shops = Shop.objects.all() return render(request, 'home/shops.html', {'shops':shops}) shops.html: {% extends 'base_template.html' %} {% block content%} <h2> Welcome </h2> {{ shops }} {% endblock%} Error: DoesNotExist at /home/shops/ Shop matching query does not exist. shopdetail = Shop.objects.get(slug=shopslug) ---> belongs to a different function -
user and company as show both
I have a system where there are two user and company registration, in separate tables, more when logging into the site, I am showing only the user.user how to show both, for example if log in user.usuario, show the user data, but if logar the company show user.company, all in a single page perfil.html <a class="text-white">Perfil </a> </small></a> <div class="row"> <div class=" col-md-10"> {{ user.usuario.nome }} {{ user.usuario.sobrenome }} </div> {% include 'bases/menu_perfil.html' %} </div> </div> <div class="card title "> <div class="card-body text-secondary"> <div class="form-row"> <div class="form-group col-md-43"> <img src="{{user.usuario.foto.medium.url}}"class="rounded-circle" width="150" height="150"> </div> <div class="form-group col-md-9"> {{ user.usuario.about}} </div> </div> <hr> <div class="form-row"> <div class="form-group col-md-12"> <img src="{% static 'img/perfil/pet.svg' %}" width="30" height="30" alt=""> {{ user.usuario.pet}} </div> </div> <div class="form-row"> <div class="form-group col-md-12"> <img src="{% static 'img/perfil/map2.svg' %}" width="40" height="40" alt=""> {{ user.usuario.cidade }} - {{ user.usuario.estado }} </div></div> -
Mac + Python3 + Django + Django-cms Segmentation Fault during page render
Mac 10.14.3 Python 3.6.5 (also tried 3.7.2) Django==1.11.20 django-cms==3.5.3 sqlite3 3.24.0 Running with ./venv/bin/python3 -Xfaulthandler manage.py runserver --noreload Migrations run fine, but page render segfaults: Performing system checks... System check identified no issues (0 silenced). March 17, 2019 - 08:04:34 Django version 1.11.20, using settings 'project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Fatal Python error: Segmentation fault Current thread 0x000070000864d000 (most recent call first): File "<local_dir>/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328 in execute File "<local_dir>/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 64 in execute File "<local_dir>/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 79 in execute File "<local_dir>/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 889 in execute_sql File "<local_dir>/venv/lib/python3.6/site-packages/django/db/models/query.py", line 53 in __iter__ File "<local_dir>/venv/lib/python3.6/site-packages/cms/utils/plugins.py", line 284 in downcast_plugins File "<local_dir>/venv/lib/python3.6/site-packages/cms/utils/plugins.py", line 75 in <genexpr> File "<local_dir>/venv/lib/python3.6/site-packages/cms/utils/plugins.py", line 75 in assign_plugins File "<local_dir>/venv/lib/python3.6/site-packages/cms/plugin_rendering.py", line 529 in _preload_placeholders_for_page File "<local_dir>/venv/lib/python3.6/site-packages/cms/plugin_rendering.py", line 329 in render_page_placeholder File "<local_dir>/venv/lib/python3.6/site-packages/cms/templatetags/cms_tags.py", line 309 in render_tag File "<local_dir>/venv/lib/python3.6/site-packages/classytags/core.py", line 153 in render File "<local_dir>/venv/lib/python3.6/site-packages/django/template/base.py", line 957 in render_annotated File "<local_dir>/venv/lib/python3.6/site-packages/django/template/base.py", line 990 in render File "<local_dir>/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 72 in render File "<local_dir>/venv/lib/python3.6/site-packages/django/template/base.py", line 957 in render_annotated File "<local_dir>/venv/lib/python3.6/site-packages/django/template/base.py", line 990 in render File "<local_dir>/venv/lib/python3.6/site-packages/cms/templatetags/cms_tags.py", line 444 in render_tag File "<local_dir>/venv/lib/python3.6/site-packages/classytags/core.py", line 153 in render File "<local_dir>/venv/lib/python3.6/site-packages/django/template/base.py", line 957 in render_annotated File "<local_dir>/venv/lib/python3.6/site-packages/django/template/base.py", line 990 in render File "<local_dir>/venv/lib/python3.6/site-packages/sekizai/templatetags/sekizai_tags.py", line 93 in render_tag … -
Django - template does not exist
I imported this library to my django project: https://github.com/percipient/django-allauth-2fa/blob/master/allauth_2fa/views.py. I keep getting this error: TemplateDoesNotExist at /setup/ base.html In template C:\Users\Davide\lib\site-packages\allauth_2fa\templates\allauth_2fa\setup.html, error at line 1 1 {% extends 'base.html' %} I don't know why it's showing that error, because i created my own setup.html at project/templates and it looks like this instead: {% extends 'main/header.html' %} {% load i18n %} {% block content %} // My urls.py looks like this: from allauth_2fa import views as allauth_2fa_views app_name = "project" urlpatterns = [ path("setup/", allauth_2fa_views.TwoFactorSetup.as_view(), name="setup"), // Other urls -
Its Posible to add more fields in django password reset?
Can i add more fields to django password reset forms? like username fields , and if username and email is valid, the password reset link will be sent to email please help me i want to password reset like this photoenter image description here -
Is there any way to change password field label in django athentication login page?
I'm using built in login view in django 2.1 Is there any way to change the password field lable? -
django template statement if != Null doesn't work
I got problem with template tag {% if ... in ... %}. I'm trying to write statements if object don't exist ( equal Null ) then don't display anything. My model got few fields for links to SOcial Media like instagram, facebook, twitter etc. and not every company got every social media as we know. The problem is that those If statements doesn't work as they should (I checked django documentation), for example if company have added links to all social medias (twitter,fb,instagram,linkedin,website) it should display images with links to them. But if company have not added any link to social medias or website, it shouldnt display images. I don't know why those statements doesn't work About images, if I remove the loop {% for ... %} {% endfor %} then it is displaying all images even if company has not associated any links so this if statements also doesnt work then comp_view.html <div class="social-media"> {% for brand in brands % {% if brand.website != None %} <a class="" href="{{ brand.website }}"> <img src="/static/icons/website.png"> </a> {% endif %} {% if brand.facebook != None %} <a class="" href="{{ brand.facebook }}"> <img src="/static/icons/facebook.png"> </a> {% endif %} {% if brand.instagram != None … -
Django - importing view from Dependency
I'm trying to use this library since i want to add 2FA Auth to my project. In order to integrate the module in my project, i need to import their views to my urls.py file, right? I tried to import SetupView, but i'm getting this error: module 'allauth_2fa.views' has no attribute 'homepage'. Here is what i understood: it looks like if i import a view from the dependency, it will only read those views from the dependency but not my own views declared on views.py. from django.urls import path from . import views from django.conf.urls import url, include from django.conf.urls import url from allauth_2fa import views app_name = "main" urlpatterns = [ path("setup/", views.TwoFactorSetup.as_view(), name="setup"), path("", views.homepage, name="homepage"), path("register/", views.register, name="register"), path("logout/", views.logout_request, name="logout"), path("login/", views.login_request, name="login"), ] Extra: SetupView will generate the page required to enable the 2FA authentication, that's why i need it. Later i will also import the other views required to have my two factor authentication fully running -
Django formtools buisness logic between forms
I am trying to implement OTP add feature in django-formtools and pyotp.(i know there is a library to do that, but I want to do it in house.) The workflow is like this. Enter captcha -> pass? -> show otp secret -> user enters generated otp code -> does the code matches with the secret? -> save secret to user model. I first made two forms, # forms.py class OTPUpdateForm1(forms.Form): captcha = CaptchaField() class OTPUpdateForm2(OTPForm): otp = forms.CharField() def clean(self): # validate otp code and then I created a formview. # views.py class NewOtpWizard(SessionWizardView): form_list = [OTPUpdateForm1, OTPUpdateForm2] success_url = reverse_lazy('otp-update') def get_template_names(self): return f'profile/editotp/step{self.steps.step}.html' def done(self, form_list, **kwargs): self.request.user.profile.save_totp_secret(data_for_step1['totp_secret']) return HttpResponseRedirect(success_url) So, I need a buisness logic code between the two forms, that is to create otp secret to verify the otp with the secret save the otp secret My questions is Where do you put the code to create otp secret? I overrided get_context_data but I think it's not the right place. It's done even when the user fails to verify the otp, resulting in a new otp secret. How do you pass the generated otp secret to OTPUpdateForm2 so that it can validate and raise ValidationError when … -
In a forms of an inlineformset how can I know which are my default form fields and which are the ones added by Django?
I have a specific formset (inlineformset), and I want to make some customization regarding the default design. I loop thru it this way: {% for form in formset %} <div class="ct-formset"> {% if form.errors %}<div>{{ form.errors }}</div>{% endif %} {% for field in form %}{{ field }}{% endfor %} {% endfor %} For each form Django add two other fields the Foreign key field and the Delete Field. Because I want to use the same code for multiple formsets, In the loop I don't request the field by name I need to know in the: {% for field in form %}{{ field }}{% endfor %} How can I know which are my default form fields and which are the ones added by Django ? -
How to pass an object between views in Django
I have the following model for my students to upload their tasks to an application that I am creating, but I have a problem, I need to pass an instance of the model between views, but since it is not serializable, I can not save it in a session attribute. Keep in mind that in one view I create the object without saving it in the database and in the other I perform operations with the object and finally I save it. Any idea how I can do this? class Homework(models.Model): code = models.AutoField(primary_key=True) student = models.ForeignKey('Student', on_delete=models.PROTECT) title = models.CharField(unique=True, max_length=100) attached_file = models.FileField(upload_to='files/homeworks/', validators=[validate_file_size], storage=gd_storage) -
How can I log a Django user into WooCommerce without prompting?
My workflow takes the user from a Django web application to a WooCommerce store. For example, they fill in example.com/register and are taken to store.com/checkout. Both applications are backed by the same LDAP database, so at the moment I prompt the user to enter their credentials a second time. This is functional, but not the greatest UX. How can I transport them from the Django to store domain and sign them into the store, without user intervention? (Because the domains are different and I expect third-party cookies to be disabled, I obviously can't generate a cookie for the store domain while still in the Django domain.) -
Allauth Django2 Social Network Login Failure: The domain of this URL isn't included
I've read every SO post on this topic and still no luck. The Facebook login button makes it all the way through directing the user to Facebook, having them enter their credentials and press submit, but then it redirects back to my domain name with an error. I've edited the Allauth template to display Code: {{ auth_error.code }}, Error: {{ auth_error.exception }} which returns Code: unknown Error: Error retrieving access token: b'{"error":{"message":"Can\'t load URL: The domain of this URL isn\'t included in the app\'s domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.","type":"OAuthException","code":191,"fbtrace_id":"xxxxxxxx"}}' I've added to Valid OAuth Redirect URIs my domain name and https://www.myapp.com/accounts/facebook/login/callback/ etc but nothing changes. I do notice that the URL when the error is thrown is https://www.myapp.com/accounts/facebook/login/callback/?code=dksjfhskdjhfskdjfskdjhfksjdhfkdsjfhksdjfh(really long code)&state=pEekQctKQlND#_=_ So URI ?code=XXX seems to be tacked onto the URI, not sure if that helps with anything. -
How to give Pafy download location in django
I have a make a web app to download audio and videos from YouTube everything is working fine but when I want to download the song or video I can't find a way to give it location for saving the file so it download it in server and my site crashed everytime I hit download views.py def download_data(request): form = MusicUrl(request.POST or None) # form see in forms.py links = MusicModelJAM.objects.all() # get all element that are present in database extension = music_down = '' # empty string for not to face UnBoundError print(request.path_info) # print(os.getcwd(), 'printing working directory for know the download loca') for link in links: pass music = pafy.new(link) # MusicModelJAM.objects.all().delete() # MusicModelJAM.objects.all().delete() user_need = request.POST.get("selected") if str(user_need) == 'Audio:m4a@128k': music_down = music.getbestaudio(preftype='m4a') # print(dir(music_down)) extension = music_down.extension # taking the extension of the music like m4a for audio or mp4 for videos music_try = '' music_try = music_down.download(filepath='') # Problem is here how can I make it so that it can download in user system return render(request, 'music/music_home.html', {'form':form, 'extension':extension, 'music':music, 'music_try':music_try}) In music_home.html After searching a lot a find a way that can download the name+extension of file but I try a lot but cant … -
Django & postgis : Error was: cannot import name 'GDALRaster'
I need to create a table called destination and has as attribute a localisation field. I work with postgres, so after some researches I found that I should work with postgis in orther to create that PointField (localisation). I am working on windows. So I installed requierements using django documentation : https://docs.djangoproject.com/en/2.1/ref/contrib/gis/install/#windows My problem is, that even if I installed gdal and other requierements using OSGeo4W as mentionned in the documentation. I still get the error : Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: cannot import name 'GDALRaster' I also change my environement variables but still have that problem. my settings : DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'shops_db', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', } } ANY HELP PLEASE. I've been stucking in this error for a long time. THANK YOU -
Displaying ManyToManyField in django template
I've been trying to display the exact values of model with ManyToMany relation but I just couldn't, all what I've achevied is receiving QuerySet <QuerySet [<Stack: PHP>, <Stack: js>]> by adding to template tags {{ brand.technologies.all }} But I would like to receive and display 2 fields, name and icon. I've tried with some loops like {% for brand in brands %} {% for technologies in brand.technologies.all %} {{ technologies.name }} {{ technologies.icon }} {% endfor %} {% endfor %} but it doesn't give any results. There is not problem with syntax because page is displaying and looks like this image models.py STACK = ( ('PHP', 'PHP'), ('js', 'JavaScript'), ... ) STACK_ICONS = ( ('/static/icons/stack/php.png', 'PHP'), ('/static/icons/stack/javascript.png', 'JavaScript'), ... ) class Company(models.Model): name = models.CharField(max_length=100, blank=False) students = models.CharField(max_length=3, choices=STUDENTS) type = models.CharField(max_length=15, choices=TYPES) workers = models.PositiveIntegerField(validators=[MinValueValidator(1)]) city = models.CharField(max_length=15,choices=CITIES) company_about = models.TextField(max_length=500, blank=False) slug = models.SlugField(unique=True) icon = models.ImageField(blank=True, null=True) image = models.ImageField(blank=True, null=True) logo = models.ImageField(blank=True, null=True) technologies = models.ManyToManyField('Stack') def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Company, self).save(*args, **kwargs) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.name # object stack relation manytomany with Company class Stack(models.Model): name = models.CharField(max_length=30, choices=STACK) icon = models.CharField(max_length=80, choices=STACK_ICONS) def … -
Django Password Reset Multiple
Hello I am trying to create password reset view in Django. I have set up the mail backend and urls and templates. Everything looks fine but when I try to send mail to reset password Django is sending multiple emails. For example 7 or 11 password reset email at the same time. How can I make it just one email for each time. Thanks a lot -
Display ImageField in UpdateView Django
I have an image field in profile model. I am not able to save the image from template. Tried saving image using django admin, it successfully saves the image but I couldn't display the image in the update view. My question is how do I save and display the image using the same template and the same form in django. Model class Profile(models.Model): image = models.ImageField(upload_to='profile_images', null=True, blank=True) profile_email = models.CharField(max_length=30, null=True, blank=True) biography = models.CharField(max_length=700, null=True, blank=True) View class ProfileSettingsView(UpdateView): model = Profile form_class = ProfileSettingsForm pk_url_kwarg = 'pk' context_object_name = 'object' template_name = 'profile_settings.html' def get_success_url(self): return reverse_lazy('users:profile_settings', args = (self.object.id,)) Template <form style="padding-left: 15px; padding-right:15px;" method="POST" enctype='multipart/form-data'> {{ form.errors }} {% csrf_token %} <h7>Note: Everything added in this section will be public.</h7> <hr> <br> <h3>Profile picture</h3> <hr> <div style="text-align:center;" class="row"> <div style="text-align:center;" class="col-lg-12"> <div class="container_image"> <div class="avatar-upload-image"> <div class="avatar-edit-image"> <input type='file' id="imageUpload" name="image" accept=".png, .jpg, .jpeg" /> <label for="imageUpload"></label> </div> <div class="avatar-preview"> <div id="imagePreview"> </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <div class="field"> <label>Full Name<span class="red-txt">*</span></label> <!-- <input class="form-control" type="text" name="full_name" value="{{ full_name }}" maxlength="60" size="50"> --> {{ form.full_name }} </div> </div> </div> <div class="col-lg-6"> <div class="form-group"> <div class="field"> <label>Email<span class="red-txt">*</span></label> {{ … -
How to connect my machine learning model written in python to a HTML page using django?
I have written a ML model in python which gives some predictions,i want to process this and display them in a web page. How do i do that using Django framework? -
Django - Model class django_otp.plugins.otp_static.models.StaticDevice doesn't declare an explicit app_label
I'm trying to use this library. When i imported the views on my own views.py using: from allauth_2fa import views i got the following error: File "C:\Users\User\Desktop\Heroku\github\backup\main\urls.py", line 20, in <module> from allauth_2fa import views File "C:\Users\User\lib\site-packages\allauth_2fa\views.py", line 23, in <module> from django_otp.plugins.otp_static.models import StaticToken File "C:\Users\User\lib\site-packages\django_otp\plugins\otp_static\models.py", line 11, in <module> class StaticDevice(Device): File "C:\Users\User\lib\site-packages\django\db\models\base.py", line 95, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django_otp.plugins.otp_static.models.StaticDevice doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I don't understand if i'm doing something wrong, or the error is in the dependency module. Can anyone help me? -
How to set Foreign key to custom user model in CreateView?
I have this custom user model 'es_user' models.py class es_user(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class es_event(models.Model): ev_name = models.CharField(max_length=100) ev_venue = models.CharField(max_length=100) ev_admin = models.ForeignKey('es_user',related_name='events',on_delete=None) Eventually, I'll be adding more fields to es_user that's why I used a custom user model. So I cannot settle for django's inbuilt user model. views.py class CreateEventView(LoginRequiredMixin,CreateView): model = es_event fields = ['ev_name','ev_venue','ev_date','ev_description'] def form_valid(self, form): form.instance.ev_admin = self.request.user return super(CreateEventView, self).form_valid(form) when I submit the form I get this error Cannot assign "<SimpleLazyObject: <User: randy>>": "es_event.ev_admin" must be a "es_user" instance. I've checked Django documentation and other stack overflow posts, but in all those the foreign key is referencing Django's inbuilt user model -
Resume Parsing using Python
I have created a resume parser and i need help to be able to extract the image that will be on the resume as well when the parser extracts all the other vital information. -
How to print prn file using linux command in python
In my case i need to print prn file using Linux command dynamically from any system. Here i am using cp filename /dev/usb/lp0 command for printing only from server machine.But I want to print from client machine not server machine. I am getting no such a file are directory. Please anyone help me to solve this. -
(Django) How to assign the username of current user to some other model in a view?
I want to assign the username field of Passengers model to the username of the current logged in user. I cant seem to do it. Below is the code. Models.py class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username class Passengers(models.Model): username = models.CharField(max_length = 100) passenger_firstname = models.CharField(max_length = 100) passenger_lastname = models.CharField(max_length = 100) passenger_age = models.CharField(max_length = 100) passenger_gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default='female') froms.py class PassengerForm(forms.ModelForm): class Meta(): model = Passengers fields = ( 'passenger_firstname', 'passenger_lastname', 'passenger_age', 'passenger_gender') views.py def passenger_info(request): if request.method == "POST": passenger_details = PassengerForm(data=request.POST) if passenger_details.is_valid(): passenger_details.username = request.user passenger_details.save() else: passenger_details = PassengerForm() return render(request,'passenger_info.html',{'passenger_details':passenger_details}) No error message is printed out but it leaves the username field blank like below: django-admin model object -
How to use my simple custom django template tag with if statement?
I am trying to use my simple tag with if in django template.As far as i know assignment tag is removed from Django 2.0 . My template tag is:- @register.simple_tag def channelpostlike(postid,userid): print(userid) postresult=ChannelPost.objects.get(id=postid) if postresult.user_like.filter(id=userid).exists(): return True else: return False I want to use it like:- {%if channelpostlike c.id request.user.id %}