Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i deploy Django to Heroku with static files
I want to publish my django application on heroku, but I am getting the error I mentioned. I researched and tried many things about it, but I could not get a positive result. remote: -----> $ python manage.py collectstatic --noinput remote: Post-processing 'css/semantic.min.css' failed! remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 194, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 138, in collect remote: raise processed remote: whitenoise.storage.MissingFileError: The file 'css/themes/default/assets/images/flags.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f96f75bdf90>. remote: The CSS file 'css/semantic.min.css' references a file which could not be found: remote: css/themes/default/assets/images/flags.png remote: Please check the URL references in this CSS file, particularly any remote: relative paths which might be pointing to the wrong location. remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: … -
Не отображаются поля формы django в модальном окне bootstrap
При создании формы отображаются все поля по прямой ссылке. При связывании формы с модальным окном бутстрап(5 без использования jquery) поля не отображаются. Модальное окно открывается, но полей формы там нет. Мой первый проект на django. Возможно не корректно передаю параметры во view, либо что-то ещё не верно. Вот код модели из файла models.py: class Order(models.Model): name = models.CharField(max_length=50, verbose_name='Имя') phone = models.IntegerField(verbose_name='Номер телефона') chosen_service = models.CharField(max_length=255, verbose_name='Выбранная услуга') ordered_at = models.DateTimeField(auto_now_add=True, verbose_name='Дата отправки') agree_policy = models.BooleanField(verbose_name='Согласен с Политикой конфиденциальности') def __str__(self): return self.name class Meta: verbose_name = 'Заявка(у)' verbose_name_plural = 'Заявки' ordering = ['-ordered_at'] Код формы из файла forms.py: class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['name', 'phone', 'agree_policy', 'chosen_service'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'phone': forms.TextInput(attrs={'class': 'form-control'}), 'agree_policy': forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'flexCheckChecked', 'checked': 'checked'}), 'chosen_service': forms.HiddenInput(attrs={'id': 'chosen_service'}), } Код из view.py: def get_order(request): if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect(request.path) else: form = OrderForm() return render(request, 'blog/form.html', {'form': form}) def service_page(request, slug): advantage = Advantage.objects.all().order_by('id') detailed_service = DetailedService.objects.all().order_by('id') slug = Service.objects.values('slug') options_detailed_service = OptionsForDetailedService.objects.all().order_by('id') response_data = { 'advantage': advantage, 'detailed_service': detailed_service, 'options_detailed_service': options_detailed_service, 'slug': slug, # 'get_order': get_order, } return render(request, 'blog/service.html', response_data) Код из urls.py: urlpatterns = [ path('', main_page, … -
How to compare DateTimeFueld with Date in Django filter funtion?
In my django app I have a MessageModel with a DateTimeField "send_date". I want to filter the messages to get all messages send a certain day (Date). How do I compare the DateTimeField with a Date to get all messages send within that day. I have try with query_result= MessageLogModel.objects.filter(received_date=myDate) but it does not show the correct results. Here is the deffinition of the Model class MessageModel(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+', verbose_name=_('Destinatario'), editable=False, null=True, blank=True) subject = models.CharField(verbose_name=_("Asunto"),max_length=50) send_date = models.DateTimeField(verbose_name=_("Fecha de envío") ,auto_now_add=True) message_body = models.TextField(verbose_name=_("Mensaje")) class Meta: db_table = 'riesgo_message' managed = True verbose_name = _("Mensaje") verbose_name_plural = _("Mensajes") def __str__(self): return self.subject -
TemplateDoesNotExist at /products/login
how can i fix this PLZ enter image description here i want to delete this directory in make it instead of what you see in image to make this looking in this one C:\Users\Katsuker\PycharmProjects\first\templates TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
How to split a long line in a Django template needed for formatting?
I have a line like this in a Django template: {{ some_prefix }}{% if obj.obj_type == A_LONG_CONSTANT %}1{% elif obj.obj_type == A_LONG_CONSTANT %}2{% endif %}{{some_suffix}}: where some_prefix might be a ( or something longer, and some_suffix might be a ) or maybe even empty. I don't know how to break this up, since putting any whitespace in such a template make it look different in a browser. Think "( hi )" instead of "(hi)". Any suggestions? You might say, "Put this in python, not Django templates." However, I'm not sure how to split it up into a tag either. It depends on the template context. I see this question, but that's just renaming variable names, which might make this thing even more heinous. I think there's probably nothing to do. -
Strange Error with Django oauth-toolkit and Azure App Service. Returns 401 {"detail":"Error decoding token."} when attempting to authenticate token
Hi I am deploying an app to Azure App Service using Django Rest Framework with OAuth2 authentication handled by django-oauth-toolkit (https://github.com/jazzband/django-oauth-toolkit). Recently when trying to connect to my React frontend I have found out that I cannot successfully authorize despite having an access token. When I make a the following API call (as suggested by the documentation): curl 'http://exampleurl.azurewebsites.net/endpoint/' -H 'authorization:Bearer <sampletoken>' I get the following response: {"detail":"Error decoding token."} I cannot recreate this error locally nor can I find any information about this error anywhere online. I even searched the repository for the error to see if I could find what triggers it, unfortunately no luck. Has anyone else ever experience this or can give me some insight on what potentially occurred in my deployment to cause this? I also deleted out my old deployment and even app service to completely start from scratch and the problem persisted. -
How to set up Django Machina custom permissions
I am new to Django and python. I have been able to alter a custom user model so that the user signup form presents the user with categories and category subforums populated from Machina tables. An example would be a user choosing the category of "Biology" (category forum) and a subcategory of microbiology (subforum of the category "Biology"). When the users view the main forum page, I only them to see a couple of site wide forums and the category/subforum they chose upon registration. I am not sure how to customize Machina to accomplish this. I found the forum permissions handler.py here: https://github.com/ellmetha/django-machina/blob/a92041c2854bee6b80d418fabd4cec5caac91dc3/machina/apps/forum_permission/handler.py#L300 It seems to offer some possible ways to accomplish what I want to do, but I am not sure of a good approach. Any suggestions for customizing which forums users have access to? -
argument of NoneType is not iterable dictoinary
Below is the dictionary I am trying to access { "skipped":"", "skip_traced":"Both", "opt_out":"Both", "filters_condition":"and" } if 'Both' not in data['skip_traced']: pass The above code show me error argument of NoneType is not iterable when I reach this command. -
Django Taggit - Autocomplete Light (Guidance with configuring)
I have Taggit fully up and running and would like to configure Autocomplete Light in order to enable the Select2 dropdown when users select their preferred tags within my application. I have installed DAL, dal_select2 along with dal_queryset_sequence libraries. I already have a form created where my users can simply upload a photo, add content and a TagField. Although, the TagField currently operates as a normal text field (But the tags do successfully save through to my Taggit app) - I'm just struggling to get the Select2 dropdown working. Here are my settings (as far as the Installed Apps are concerned: Settings.py INSTALLED_APPS = [ 'core.apps.AConfig', 'users.apps.UConfig', 'crispy_forms', 'emoji_picker', 'taggit', 'dal', 'dal_select2', 'dal_queryset_sequence', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] Within my Views.py from dal import autocomplete class TagAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Tag.objects.none() qs = Tag.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs URLs.py from core.views import TagAutocomplete urlpatterns = [ url( r'^tag-autocomplete/$', TagAutocomplete.as_view(), name='tag-autocomplete', ), ] Forms.py import dal from dal import autocomplete from taggit.models import Tag class PostForm(autocomplete.FutureModelForm): tags = forms.ModelChoiceField( queryset=Tag.objects.all() ) class Meta: model = Post fields = ('__all__') … -
Is there any way to change the email scope to username scope in django
I just would like to know how to copy the email scope to the username scope in Django and for Google OAuth 2.0. -
Chained dropdown validation error. Form works
Creating a chained drop down following a tutorial. Everything works fine but it is throwing an unnecessary validation error. It is a basic 3 field form creating a person object with name, country and city. Views.py def person_create_view(request): form = PersonCreationForm() if request.method =='POST': form = PersonCreationForm(request.POST) if form.is_valid(): form.save() return redirect('person_add') return render(request, 'store/ho.html', {'form': form}) Forms.py class PersonCreationForm(forms.ModelForm): class Meta: model = Person fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id = country_id) except(ValueError, TypeError): pass elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') In forms.py line 7 where it says- self.fields['city'].queryset = City.objects.none() this line is throwing a validation error when I try to submit the form. In the tutorial they add the if/else argument and that solves the problem and error goes away. error: "Select a valid choice. That choice is not one of the available choices" In my case the error still shows up. If I ignore it and re select the city and submit, it works just fine. It is almost like having a pause at that line and the system suddenly realizes that there is more code. How do I fix … -
Is it safe to call emit_post_migrate_signal from within a Django migration?
Background My original issue that lead me to this was my desire to create a Group within a django migration (not a problem) and then also assign permissions to that Group within a migration (problem arises here). It seems that in Django that ContentTypes and Permissions are created post-migration. So migrations cannot assign Permissions to Groups because the Permissions don't exist yet. ContentType and Permission generation is triggered by the post_migrate signal, which appears to be sent automatically after all migrations have been applied. There is this work around, in which you manually call emit_post_migrate_signal from within your migration. This will generate all ContentTypes and Permissions, and then the migration can indeed successfully apply them to the Group. Question My question is: is this actually safe to do? I can't find any documentation on the emit_post_migrate_signal function, and emitting a post_migrate signal in the middle of a migration seems like a recipe for something to go wrong (either now or in the future). -
Migration from Django 2 to 3 and url with localization
I am using Django 3.2.3, Apache and Daphne. Daphne is very slow. I use Apache like a proxy to send the request to Daphne : <VirtualHost *:443> AllowEncodedSlashes On ServerName mysite.com ServerAdmin admin@gmail.com ProxyPass "/" "http://127.0.0.1:8001/" ProxyPassReverse "/" "http://127.0.0.1:8001/" Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods "GET" env=CORS Header set Access-Control-Allow-Credentials "false" env=CORS SSLCertificateFile /etc/letsencrypt/live/****/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/***/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> I launch Daphne with the command : daphne -p 8001 asgi:application When I access to my website, the log of Daphne are : 2021-06-04 21:17:17,821 INFO Adding job tentatively -- it will be properly scheduled when the scheduler starts 2021-06-04 21:17:17,865 INFO Added job "my_job" to job store "default" 2021-06-04 21:17:17,866 INFO Scheduler started 2021-06-04 21:17:17,909 INFO Starting server at tcp:port=8001:interface=127.0.0.1 2021-06-04 21:17:17,912 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2021-06-04 21:17:17,913 INFO Configuring endpoint tcp:port=8001:interface=127.0.0.1 2021-06-04 21:17:17,919 INFO Listening on TCP address 127.0.0.1:8001 2021-06-04 21:17:20,053 INFO Running job "my_job (trigger: cron[second='*/20'], next run at: 2021-06-04 21:17:20 CEST)" (scheduled at 2021-06-04 21:17:20+02:00) 2021-06-04 21:17:20,054 INFO Job "my_job (trigger: cron[second='*/20'], next run at: 2021-06-04 21:17:20 CEST)" executed successfully 2021-06-04 21:17:40,105 INFO Running job "my_job (trigger: cron[second='*/20'], next run at: 2021-06-04 21:17:40 CEST)" (scheduled at 2021-06-04 21:17:40+02:00) … -
Models Mixin ManytoMany
I want to implement in django a model mixin. I have in mixin.py: class RightsModelRelation(models.Model): user_link = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False, default=None, related_name="%(class)s_rights_user") right_to_view = models.BooleanField(default=True) right_to_change = models.BooleanField(default=False) right_to_delete = models.BooleanField(default=False) class RightsModelMixin(models.Model): rights_link = models.ManyToManyField(RightsModelRelation, default=None, related_name="%(class)s_rights_link") models.py: class Address( RightsModelMixin,models.Model): lastname = models.CharField(max_length=255, default="", ) firstname = models.CharField(max_length=255, default="", blank=True, null=True) But this don't work. Can anyone help me to implement a manytomany models mixin? -
VSCode Permission issues for File creation and Renaming in a Django App
I'm having an issue with creating another python file inside of the main app of my Django tree (I'm still learning Django so I'm not sure of the terminology). When I try to create a file inside of main part of the app named tweets I get this error. Unable to write file '/Users/ak/Dev/tweetme/tweets/forms.py' (NoPermissions (FileSystemError): Error: EACCES: permission denied, open Then I said fine, I'll just create the file in another directory and move it to the tweets folder, When I attempt this, I get the following error. Error: EACCES: permission denied, rename '/Users/ak/Dev/tweetme/tweetme/forms.py' -> '/Users/ak/Dev/tweetme/tweets/forms.py' From what I can read only people having this issues have downloaded some SSH shelling mod, which I don't have, nor do I know what that is. This problem came on suddenly, When I started this project I had no problem created files inside of the tweets folder. Does anyone have any insight into this?? Or how I can fix this? -
implementing a multi-filter search in Django
I have a search bar for searching jobs. There are 3 filters namely description, categories and locations. For description, I want to search a job by a company name, job title or job description. Even if the user inputs, "company name and job title", i should retrieve a correct match not exactly but somewhat close. How do I get this? models.py class Internship(models.Model): recruiter = models.ForeignKey(Recruiter, on_delete=models.SET_NULL, null=True) internship_title = models.CharField(max_length=100) internship_mode = models.CharField(max_length=20, choices=MODE_CHOICES) industry_type = models.CharField(max_length=200) internship_desc = RichTextField() class Recruiter(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) company_name = models.CharField(max_length=100) views.py def user_search_internship(request): if request.method == "POST": internship_desc = request.POST['internship_desc'] //can be title, desc, company or a combo internship_ind = request.POST['internship_industry'] internship_loc = request.POST['internship_location'] internships = Internship.objects.all() if internship_desc != "" and internship_desc is not None: internships = internships.filter(internship_title__icontains=internship_desc) context = { } return render(request, '', context) -
Django Rest Framework SQL Query CORS
I am building a tool where users can enter certain parameters and when they hit submit, it will query a mssql database and return some data. The data is passed through Django Rest Framework into a React frontend. The database is massive, so some queries might take several minutes to return. The issue I'm having is that for queries that take a long time, in the Network tab the status show CORS error: MissingAllowOriginHeader. The data returns fine for shorter queries, for longer queries after 30-45 seconds of loading I will get the CORS error. Also, note that this only occurs on a production IIS server, and works fine on my local server. I have tried the following in my settings.py already CORS_ALLOW_ALL_ORIGINS = True ACCESS_CONTROL_ALLOW_HEADERS = True How I'm getting the data from the sql server class SearchView(APIView): def post(self, request, *args, **kw): with connections["mssql"].cursor() as cursor: cursor.execute(sql_str) all = cursor.fetchall() How I'm making the request from React axios .post(process.env.REACT_APP_SEARCH, holder, { headers: { Authorization: "JWT " + sessionStorage.getItem("refresh"), "Content-Type": "application/json", }, }) -
Change model value to None in Query set by checking a field value inside it from Manager
I have a Manager fucntion that prefetches cover photo of the model. the cover_photo (Foreign key to CoverPhoto) model has a field is_verified. Is there a way to make the cover_photo object None if it has is_verified=False from the manager? So that from normal user point view I can hide unverified photos but still need other things and from admin side I can see all photos in List get query. return self.prefetch_related( Prefetch( "deity_list", queryset=Deity.objects.select_related("cover_photo") .filter(is_verified=True, site_visible=True), ), )``` -
modulenotfounderror no module named
I need to implement a function in a file where it executes a python script in another folder. python_project . ├── a │ ├── funcs (folder) | | |--->myfunc.py │ └── my_custom_lib.py |--calc.py in calc.py I have the following function: def anotherfunction(func): os.system('python3 a/funcs/myfunc.py') When I execute it, I got an error enter code here *PS: The main application is in Django -
Steps to deploy ajax django rest api app for production
I created a back-end using Django Rest Framework, And a frontend using some html CSS and ajax for api calls, it's working well but now how can I deploy that app for product -
how to send custom message with activation Email in Django Djoser?
After signup request I am getting this Email to activate my account. I m using Djoser framework for user Authentication system. How can I change the message in email but the activation link should remain same. Email: You're receiving this email because you need to finish activation process on localhost:8000. Please go to the following page to activate account: http://localhost:8000/activate/MQ/5r7-28cd6539635652113a77 -
pgAdmin Blocked by Quick Heal Total Antivirus
I am Using Postgres for the first time. So while trying to view the data in my table Quick Heal Blocked it by saying that was a Ransomware. Here is the report(given below): Report for - Total Security Ransomware Protection Friday, 04 June, 2021, Time 23:55:08 Total Security Version - 19.00 Virus database - 04 June 2021 ------------------------------------------------------------------------------------------- Detected: HEUR:Ransom.Win32.InP in D:\PostgreSQL\pgAdmin 4\bin\pgAdmin4.exe Action taken: Quarantined --------------------End of Report---------------------- Why did this happen and how to make everything ok ? -
I can't get the login page after submitting logout, django, "from django.contrib.auth import login, views as auth_views"
https://stackoverflow.com [[from django.urls import path, include from users_app import views from django.contrib.auth import login, views as auth_views urlpatterns = [ path('register/', views.register, name='register'), path('login', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout', auth_views.LoginView.as_view(template_name='logout.html'), name='logout') ] ###Here is my login and logout concept it is in base file {% if user.is_authenticated %} <div class="form-inline my-2 my-lg-0"> <div class="p-2 bg-dark text-white">Logged in as {{ user.username }}</div> <a href="{% url 'logout' %}"> <button class="btn btn-info my-2 my-sm-0" type="submit">Logout</button> </a> </div> {% else %} <a href="{% url 'login' %}"> <button class="btn btn-success mr-2 my-2 my-sm-0" type="submit">Login</button> </a> <a href="{% url 'register' %}"> <button class="btn btn-primary my-2 my-sm-0" type="submit">Register</button> </a> {% endif %} ]1 -
how to connect AWS RDS to ECS FARGATE Container using DJANGO and postgreSQL
Im not sure what is wrong here but iam using django docker-compose postgresql and i am trying to connect the db that I have created using AWS RDS to the ECS Container. Following the instructions on AWS Docs, I have created a role with a policy applied to the task definition using the AWS Secret Manager. Also in the Security Group for RDS, I have given access to the security group of ECS Fargate Container. Now the issue, the task cannot start. They always say pending... then become stopped please find the task traceback below: 6/4/2021, 1:47:53 PM return func(*args, **kwargs) backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor backend 6/4/2021, 1:47:53 PM return self._cursor() backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor backend 6/4/2021, 1:47:53 PM self.ensure_connection() backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner backend 6/4/2021, 1:47:53 PM return func(*args, **kwargs) backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection backend 6/4/2021, 1:47:53 PM self.connect() backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner backend 6/4/2021, 1:47:53 PM return func(*args, **kwargs) backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect backend 6/4/2021, 1:47:53 PM self.connection = self.get_new_connection(conn_params) backend 6/4/2021, … -
Differentiate between an static and a dynamic QR by received data
Right now the frontend side reads a QR that can be static or dynamic and it's sent to the backend (Django). This QR it's sent as a raw data string and I need to differentiate between this string represents a static or dynamic QR. Is there any way to do that?