Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NameError: name 'urlpatterns' is not defined using i18n_patterns
I have problems writing the urls for translation. According to this question I understand that it is because I have += so I need to put this = the bad thing is that I have to translate all my urls I can't leave any outside of i18n, what can I do to include all my urls there? from . import views from django.urls import path from django.conf.urls.i18n import i18n_patterns app_name='Clientes' urlpatterns+= i18n_patterns( path('',views.list_clientes,name='clientes_list'), path('add',views.create_clientes.as_view(),name='clientes_add'), path('edit/<int:pk>',views.edit_clientes.as_view(),name='clientes_edit'), path('<int:pk>/',views.detail_clientes.as_view(),name='clientes_detail'), path('delete/<int:pk>',views.eliminar_cliente.as_view(),name='clientes_delete'), ) -
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='prod.******', port=9200)
please I have elasticsearch on prod server , i changed all the url on my django project to localhost , but still show me this error ! any solution please ! hellp es = Elasticsearch('http://localhost:9200/') -
How do I upload all the files in a django app to a git brand new repository?
I'm using Django in PyCharm for a simple project. I have a github account, git installed on my environment and github desktop, but I can't figure out how to upload all the files in my entire app project to a git repository all at once, to then view it on github. I haven't been using Git at all throughout the project and it has cost me when making irreversible mistakes. So what's the easiest way to use Git/github with Pycharm. i got the extension for it but I find the interface a bit confusing. -
Django, JWT, React redirect to different page base on different group after log in
I have 2 roles which are member and staff, and i want to redirect to the different pages depend on the users' roles using username and password e.g. after logging in as a member would redirect to member page and as a staff would redirect to onlystaff page. How I can do it. I'm using React Django JWT and Material UI. the code: axios.js const baseURL = 'http://127.0.0.1:8000/api/'; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem('access_token') ? 'JWT ' + localStorage.getItem('access_token') : null, 'Content-Type': 'application/json', accept: 'application/json', }, }); axiosInstance.interceptors.response.use( (response) => { return response; }, async function (error) { const originalRequest = error.config; if (typeof error.response === 'undefined') { alert( 'A server/network error occurred. ' + 'Looks like CORS might be the problem. ' + 'Sorry about this - we will get it fixed shortly.' ); return Promise.reject(error); } if ( error.response.status === 401 && originalRequest.url === baseURL + 'token/refresh/' ) { window.location.href = '/login/'; return Promise.reject(error); } if ( error.response.data.code === 'token_not_valid' && error.response.status === 401 && error.response.statusText === 'Unauthorized' ) { const refreshToken = localStorage.getItem('refresh_token'); if (refreshToken) { const tokenParts = JSON.parse(atob(refreshToken.split('.')[1])); const now = Math.ceil(Date.now() / 1000); console.log(tokenParts.exp); if (tokenParts.exp > now) … -
Why is collectstatic only detecting admin static files?
I'm using S3 to store my static files, but I'm having an issue where only the admin static files are uploading to the bucket. I expected to see the css and other folders from inside static upload to the bucket, but instead, this is all I got: static/ - admin/ - flags/ What can I do to get my app's static folder to upload also? Looking at other answers to this question, it seems like the main difference is that my project uses django-sass-processor, but I'm not sure why that would mean my entire folder is not picked up. Project folder structure: backend/ - accounts/ - core/ -- settings.py -- ... - static/ - templates/ settings.py USE_S3 = os.getenv('USE_S3') == 'TRUE' if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder', ] SASS_PROCESSOR_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
Split video into images with OpenCV on Django
I am trying to split a video into images. Each image should be store individually into an object "UserCapturedData". At the moment, here is the code i use: cap = cv2.VideoCapture(userData.file.path) while cap.isOpened(): # Extract the frame ret, frame = cap.read() if not ret: continue filename = datetime.now().strftime('%Y.%m.%d.%H.%M.%S') path = "media/"+filename+"-"+str(count+1)+'.jpg' cv2.imwrite(path, frame) # It works until here... tempImageFile = ContentFile(File(open(path,'r'))) # What should i pass here???? UserCapturedData.objects.create(profile=userData.profile, file=tempImageFile) (...) In my case, UserCapturedData.file is : file = models.FileField(_('File'), blank=True) Thanks for your help! -
Dynamic URL Django problems
Im making a journal-program for dental offices, using django. I want to make dynamic URLs for the clinics page and for individual patients aswell. I want the URLs to inherent the id's of both the clinic and patient. The models.py: class klinik(models.Model): klinikid = models.CharField(max_length=200, null=True) class patient(models.Model): id_nr = models.CharField(max_length=200, null=True) The views.py: def klinik(request, k_id): klinikker = klinikker.objects.get(klinik_id=k_id) patients= patient.objects.all() return render(request,'DentHelp/klinik.html', {'patients':patients}) def registering(request, fd): patientsid = patient.objects.get(id_nr=fd) return render(request,'DentHelp/registrering.html') The URLS.py path('klinik/<str:k_id>/', views.klinik), path('registrering/<str:fd>/', views.registering), Something must be right, because the patients page called registrering is loading nicely, however the klinik page says the object hasnt been declared. Do you see any mistakes? -
Omit base resolver edge resolution in an aggregation query
I'm returning aggregate data for a model, I have: Objects { byColor { red blue } } As my query, then in graphene I have: class ObjectsQuery(DjangoObjectType): class Meta: model = Objects def resolve_by_color(self, _): return self.iterable.aggregate(...) I'm having a performance issue because it looks like a query for all Objects is being executed, even though the results of that query aren't included in any edges. Is there a way to avoid this Objects.objects.all() query from running? -
Some task are not processing using Django-Q
I have a django Q cluster running with this configuration: Q_CLUSTER = { 'name': 'pretty_name', 'workers': 1, 'recycle': 500, 'timeout': 500, 'queue_limit': 5, 'cpu_affinity': 1, 'label': 'Django Q', 'save_limit': 0, 'ack_failures': True, 'max_attempts': 1, 'attempt_count': 1, 'redis': { 'host': CHANNEL_REDIS_HOST, 'port': CHANNEL_REDIS_PORT, 'db': 5, } } On this cluster I have a scheduled task supposed to run every 15 minutes. Sometimes it works fine and this is what I can see on my worker logs: [Q] INFO Enqueued 1 [Q] INFO Process-1:1 processing [oranges-georgia-snake-social] [Q] INFO Process-1 created a task from schedule [2] [ My Personal Custom Task Log] [Q] INFO Processed [oranges-georgia-snake-social] But other times the task does not start, this is what I get on my log: [Q] INFO Enqueued 1 [Q] INFO Process-1 created a task from schedule [2] And then nothing for the next 15 minutes. Any idea where this might come from ? -
how to make a post request and get the radio button values in django
I'm doing a website in django but this is the first time i use this framework so i'm not so used to it. I need to save some information on a DB, and i need to take these information from some radio buttons. I tryied so many ways to get the data but nothing worked. So i'd like to ask how to get these data in models.py from a template.html. This is the code in views.py: def question1(request): form = CHOICES(request.POST) if request.method == 'POST': form = CHOICES(request.POST) if form.is_valid(): selected = form.cleaned_data.get("NUMS") return render(request, 'q1.html', {'form': form}) This is the template question1.html: <form class="form-inline" method='POST' action="" enctype='multipart/form-data'>{% csrf_token %} {% csrf_token %} {{form.path}} </form> Then there is the form in forms.py: NUMS = [ ('one', 'one'), ('two', 'two'), ('three', 'three'), ('four', 'four'), ('five', 'fives'), ] class CHOICES(forms.Form): NUMS = forms.ChoiceField(choices=NUMS, widget=forms.RadioSelect) I checked and I think that the problem could be the request.method that is GET insted of POST. So how can I make a POST request? Thank you -
Update a Python variable that is interrogating JIRA API that is subsequently presented on a template page
I have a variable that is being written from a JIRA call using the JIRA Python Library - when restarting the development server, the values in the variable are updated of course as the connection to JIRA is re-established. I am trying to understand the best way to update the value in the variables - either on a timed basis, or on each refresh/visit to the Dashboard. My views.py file below: views.py # Emergency Changes Query jira_emergency_changes = jira.search_issues('labels = change-audit AND resolution = Unresolved').total class Dashboard(LoginRequiredMixin,View): def get(self, request): greeting = {} greeting['heading'] = "Dashboard" greeting['pageview'] = "Tooling" greeting['jira_emergency_changes_render'] = jira_emergency_changes return render(request, 'hub/dashboard.html',greeting) Thanks in advance :) -
Facing Internal Server Error With Django Requests When Adding A Product
ISSUE: I ran my project and tried adding a product through Django's Jet Dashboard, but it's giving me errors. Project Repository: https://github.com/Bilal815/ecommerce_storee My Redis giving warning: enter image description here My Logging Messages: enter image description here POST request's response: enter image description here Question: What do I do here? Is it an SSL issue or an elasticsearch issue? I've tried disabling elasticsearch but to no avail and also tried adding product via MySQL and it worked! Thank you for any help! -
Why i cant get the prefetched related object in DJANGO?
I want to get the midia with the thumbnail = True for every galeria using the prefetch related. class Midia(Base): galeria = models.ForeignKey(Galeria, on_delete=models.CASCADE, related_name= "midias") thumbnail = models.BooleanField('Thumbnail ', default=False) video_thumbnail = models.URLField(blank = True) imagem = StdImageField(upload_to='midias/', blank=True, delete_orphans=True) class Galeria(Base): titulo = models.CharField('Título', max_length=100) descricao = models.TextField('Descrição', blank= True) I did it using this code in the view: galerias = Galeria.objects.prefetch_related(Prefetch('midias', queryset= Midia.objects.filter(thumbnail = True))).all() And this in the HTML: {% for galeria in galerias %} {% with thumbnail=galeria.midias.first %} {% if thumbnail %} {% if thumbnail.imagem %} <img src="{{ thumbnail.imagem.url }}" alt="" > {% else %} <img src="{{ thumbnail.video_thumbnail }}" alt=""> {% endif %} {% else %} <img src="generic image" alt="" > {% endif %} {% endwith %} But why when i try to do this: {% with thumbnail=galeria.midias %} It returns None. Checking the sqls hits in the database the galeria.midias.first does not appear. Why when i use galeria.midias it returns None? -
Django - How to import csv data with a model that has a foreign key to an instance of the same model?
I'm trying to import data from a CSV file on a model Category that looks something like this: class Categories(BaseModel): shop_id = models.SmallIntegerField(default=1, blank=True) parent_id = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) name_en = models.CharField(max_length=255) name_fr = models.CharField(max_length=255, null=True, blank=True) I am working on a script to load the csv and read the data to create a model instance, but how can I get the Categories instance related to parent_id when it has not been created yet. -
What platform would be best to host my Ecommerce site?
I currently have a Shopify website but I have now learned Python and Django and I am building out my own ecommerce site. It's a relatively small website with 1 current product, some images and a blog with a number of articles. Can anyone please recommend a platform that would work best for hosting my page and domain? Shopify is currently 30euros and I would hope that I could reduce this with AWS or GCP although I am new to web dev and may be incorrect. Any advice is highly appreciated. -
django debug toolbar unit testing version change
I'm updating a legacy Django (version 2.2.27) running on Python 3.7.7 to use an upgraded version of django-debug-toolbar (version 2.2.1) because of a Dependabot alert. The alert was about possible SQL injection. Is it possible to write unit tests to determine if the version update does what it's supposed to? Any resources, links or suggestions are welcome. -
Password Reset Confirm did'nt work Django
I'm trying to Reset password with Django but after sending email to write new password it renders me to django adminstration page enter image description here from django.urls import path from . import views from django.contrib.auth import views as auth_views from django.contrib.auth.views import LoginView,LogoutView from .forms import UserLoginForm urlpatterns = [ path('login/',LoginView.as_view( template_name='registration/login.html', authentication_form=UserLoginForm),name='login'), path('logout/',LogoutView.as_view(),name='logout'), path('signup/',views.UserCreateView.as_view(),name='signup'), path('user_profile/<int:pk>/', views.UserProfileView.as_view(),name='user-profile'), path('user/<int:pk>/update', views.UpdateUserProfileView.as_view(),name='update-profile'), path('user/password/', views.ChangePasswordView.as_view(),name='password-change'), # Process of reset the passwords path('reset_password/', auth_views.PasswordResetView.as_view( template_name='registration/reset_password.html'), name='reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view( template_name='registration/password_reset_sent.html'), name='password_reset_done'), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view( template_name='registration/password_reset_form.html'), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view( template_name='registration/password_reset_done.html'), name='password_reset_complete'), ] and password_reset_form.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} {% if validlink %} <h3>Change password</h3> <form method="post"> {% csrf_token %} {{ form|crispy}} <button type="submit">Change password</button> </form> {% else %} <p> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %} {% endblock %} -
Django CreateView: ModelForm not saving to db;
My modelform is not saving data to the database and using a CustomUser Model and a Profile model too. Here is my CustomUser model class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True, null=True) # Personal details first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) dob = models.DateField() gender = models.CharField(max_length=100, choices=SEX) profile_pic = models.ImageField(upload_to='images',null=True) Here is my Profile Model class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) # Education school_name = models.CharField(max_length=200) school_address = models.CharField(max_length=200) lga = models.CharField(max_length=100) school_state = models.CharField(max_length=200) course = models.CharField(max_length=100) level_of_study = models.PositiveIntegerField() When the user clicks on the student registration link, it loads the CustomUser Fields and the Additional fields in the Student Class. I need a proper way of saving these data to the database so that when under the CustomUser Model i will see the user's details and also when i check the Student Model i will see the user's details who are students too. -
wagtail: How to dynamically limit the number of Parent Key objects in the admin panel (page model)?
Here is my model: class Store(Page): ..... panels=[InlinePanel(pr)] class pr(orderable): .... store = ParentalKey(Store,...) I want each user to have a different limit on the number of PRs.and raise ValidationError if exceeds the limit I try to use WagtailAdminPageForm and override clean() to detect the number of PRs, but I have a problem. delete button not really delete item, it's just "display:none". so, I can't use attribute of self.data "store_pr-TOTAL_FORMS" to detect the number of PRs and raise ValidationError. When the user exceeds the limit, this form cannot be saved, even if the PR is deleted on the form, because the length of the PR sent to the server will only increase and will not decrease -
Return inital value in admin change/add form field
I need return only current user on add/change admin model field: In my admin/model the field fk user, return a list of users, independent if the current user is_admin or not: How put initial value only current user, and nothing more. admin.py class AdminProductModel(admin.ModelAdmin): inlines = [AdminProductImages,AdminProductFeatures] model = Product def formfield_for_dbfield(self, db_field, request, **kwargs): formfield = super(AdminProductModel, self).formfield_for_dbfield( db_field, request, **kwargs) if db_field.name == 'user': formfield.widget.can_add_related = False formfield.widget.can_change_related = False return formfield def product_thumb(self, obj): # return HTML link that will not be escaped return mark_safe( '<img src="%s" style="width:30px;height:30px;">' % (ProductImages.objects.filter(product=obj).first().image_file_w200_png.url) ) product_thumb.short_description = 'Preview' list_display = ['product_thumb','user','slug','created_at'] list_display_links = ('slug','product_thumb') exclude = ['slug','product_title_seo'] def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(user_id=request.user) models.py class Product(models.Model): user = models.ForeignKey(User,verbose_name = u'usuário', on_delete=models.CASCADE) #...otherfields -
How to put api in Django?
I have just started learning Django. I am a beginner. I have a project related to cryptocurrency, and it is supposed that the white paper we import through the API will get the price and volume from the desired site (example: coinmarketcap.com), but no matter how much I search, I do not know how to implement this piece.Can you help me? -
How to keep sidebar remain open when page reload in django?
Can you guys help me? I badly need help, this problem is taking forever and really consumed a lot of the allotted time. There's a project that I currently working on where there's a sidebar on the admin panel. I wanted to keep the sidebar remain open or keep its state whenever the page reloads to other link. Whenever I click the submenu item or an active link on the sidebar header like the "Access" on the Dashboard, the sidebar closed and getting back to the way it was. I've searching for possible solutions but nothing solved my problem. Here's my base.html: <body> <div class="wrapper"> <!-- Sidebar --> <nav id="sidebar" class="menu"> <div class="sidebar-header"> <a href="/"> <img src="{%static 'img/w1_yellow.png'%}"> </a> </div> <ul class="list-unstyled components pre-scrollable nav-menu" id="nav-menu"> <!--Dashboard--> <li class="main-list active"> <a href="#homeSubmenu" role="button" data-toggle="collapse" data-parent="#nav-menu" aria-expanded="false" class="dropdown-toggle"> <i class="fas fa-tachometer-alt mr-2"></i>Dashboard</a> <ul class="collapse list-unstyled sub-menu" id="homeSubmenu"> <li {% block nav_dash-access%}{% endblock %}> <a href="/attendance/access" >Access</a> </li> <li {% block nav_dash-activity%}{% endblock %}> <a href="/activity/dashboard">Activity</a> </li> <li {% block nav_dash-facility%}{% endblock %}> <a href="/booking/admin">Facility</a> </li> <li {% block nav_dash-mentors%}{% endblock %}> <a href="/account/dashboardmentors">Mentor</a> </li> </ul> </li> <li class="main-list"> <a href="#pageSubmenu" data-widget="pushmenu" role="button" data-toggle="collapse" data-parent="#nav-menu" aria-expanded="false" class="collapse-toggle"> <i class="fas fa-bookmark mr-2"></i>Booking</a> <ul … -
Create a python object with a date field 3 months from now
I'm learning python, hence this is probably an obvious solution for some, but I am trying to create a class that, whenever created, has a test field with a date value of three months from now. My class is as follows: class Something(models.Model): test = models.DateTimeField(default=self.get_date()) def get_date(self): today = datetime.date.today() return today + relativedelta(months=1) I thought that I could define it as a function and then call it to set the date. Can someone advise what's wrong here? Any links to relevant documentation would also be appreciated, thank you. -
Django not show checkbox after submit form
I create control_form.html for show and edit status of checkbox like this code. control_form.html {% for device in device %} <!-- Rounded switch --> <form action="addStatus" method="post"> {% csrf_token %} <label class="switch"> <input type="checkbox" name="status" onChange="this.form.submit()" {% if device.status %} checked{% endif %}> <span class="slider round"></span> </label> </form> {% endfor %} When form submit it will send data to addStatus() for update database. After that, it will back to control_form.html with data update. views.py def controlForm(request): status = 0 data=Device.objects.all().filter(api_key='003') device = {'device':data} return render(request,'control_form.html', device) def addStatus(request): status =request.POST.get('status') if status == "on": device_item = Device.objects.get(api_key='003') device_item.status = 1 device_item.save() else: device_item = Device.objects.get(api_key='003') device_item.status = 0 device_item.save() return render(request, 'control_form.html') The problem is after update database in addStatus(). The control_form.html not show checkbox. How to fix it? -
DRF SearchFilter in ListAPIViews
I'm working on Django==3.2.7, djangorestframework==3.12.4 and django-filter==21.1. and React for the frontend What I would like to do: Return Job Offer objects that contains words from search (Search fields job_title and localistation) Remove useless words like ('in', 'a', 'an', 'the', 'at', 'for', 'to') in search here an example of the url: {{URL}}/api/v1/job-offers/jobs/?search=Chef in Texas allowed_methods = ['GET'] What I've done so far in my (ListAPIView): class JobOfferListAPIView(generics.ListAPIView): permission_classes = [permissions.IsAuthenticated] queryset = JobOffer.objects.all() serializer_class = JobOfferSerializer filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend] search_fields = ['job_title', 'localisation'] ordering_fields = ['user', 'is_active'] filterset_fields = ['user', 'is_active', 'job_title', 'type_of_job', 'start_date', 'salary', 'localisation'] def get_queryset(self, *args, **kwargs): exclude_words = ['in', 'a', 'an', 'the', 'at', 'for', 'to'] keywords = self.request.GET.get('search').split(' ') keywords = [keyword for keyword in keywords if keyword not in exclude_words] if keywords: for keyword in keywords: queryset = queryset.filter( Q(job_title__icontains=keyword) | Q(localisation__icontains=keyword) ) print(queryset) return queryset Problème: When i'm printing queryset i can see filtered Job Offers in terminal but not return in Postman. Terminal Screen: Postman Screen