Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in models folder "doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS"
I can't find a solution for the following error: RuntimeError: Model class users.models.User.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The INSTALLED_APPS: LOCAL_APPS = [ "api.users", "api.achievements", "api.others", ] # https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS Models folder users/models/__init__.py: from .User import * # noqa from .Profile import * # noqa users/models/User.py: """ User related models """ from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse from django_countries.fields import CountryField from api.others.constants import GENDER class User(AbstractUser): """ Default custom user model for Dezumi API. If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. """ birth_date = models.DateField(null=True, blank=True) country = CountryField(null=True, blank=True, blank_label='Select country') gender = models.CharField(choices=GENDER, max_length=6, null=True, blank=True) is_verified = models.BooleanField( default=False, ) def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) The app is on installed_apps, so what could it be? Something with the init.py? -
"Incomplete response received from application" when i reload url
i am new to hosting a Django application on a shared hosting using cpanel. am running a django==2.1 version. after all it requirres to setup and host the appication , when i reload the url, it gives me the above error. this is the error log. cpanel error log this is the error from terminal when i run manage.py runserver terminal error log can some one pliz help figure out the problem thanks. -
If else statement in django template based on request.session data
I'm trying to prevent/allow the user from clicking a button depending on whether a key is present in the request.session data. It works for blocking it, but once the key is added to the session, that isn't reflected on the webpage/template and the key remains blocked. I presume I'll have to do this in JS but I'm not sure how to approach it. Any ideas? Thanks {% if choices not in request.session %} <form class="submit-form" action="{% url 'search' %}" method="post" onsubmit="return false;"> {% csrf_token %} <input type="submit" class="show-more-button cunt" style="margin-left: 5px" name="mybtn" value="Search" data-bs-toggle="popover" data-bs-placement="right" data-bs-trigger="focus" data-bs-content="Please select one or more ingredient"> </form> {% else %} <form action="{% url 'search' %}" method="post"> {% csrf_token %} <input type="submit" class="show-more-button" style="margin-left: 5px" name="mybtn" value="Search"> </form> {% endif %} if request.POST.get('button_color') == 'green': selected_ingredients = request.session.get('choices', []) selected_ingredients.insert(len(selected_ingredients), ingredients_name) request.session['choices'] = selected_ingredients request.session.modified = True -
i have some issue when creating django project. i cannot create new project whenever i ran cmd i get error saying
C:\Users\Dnyane\Documents\file_1>django-admin startproject a CommandError: [WinError 2] The system cannot find the file specified:'C:\Users\Dnyane\Documents\file_1\a' -
Prepopulate Django ModelForm With all records
I am trying to prepopulate my form with all records but i am receiving error 'QuerySet' object has no attribute '_meta' , I tried just passing my queryset through initial while i get no error the fields in my template aren't rendering initial={runninghours} my views.py: def runninghours(request): runninghours = RunningHours.objects.all() form = RunningHoursModelForm() form_populated = RunningHoursModelForm(initial={runninghours}) if request.method == 'POST' and 'form-create' in request.POST: form = RunningHoursModelForm(request.POST) if form.is_valid(): form.save() return redirect(request.path_info) context = {"form": form, "rhs": form_populated} return render(request, 'runninghours.html', context) The template: <form method="POST" action=""> {% csrf_token %} <td>{% render_field rhs.name %}</td> <td>{% render_field rhs.current_runninghours %}</td> <td>{% render_field rhs.last_runninghours %}</td> <td>{% render_field rhs.last_modified %}</td> <td> <input type="hidden" name="update_runninghours_id" value="{{ rhs.pk }}" /> <input name="form-delete" type="submit" class="button1" value='Update Runninghours' /></td> </form> the models.py: class RunningHours(models.Model): name = models.CharField(max_length=100) current_runninghours = models.IntegerField(blank=True,null=True) last_runninghours = models.IntegerField(blank=True,null=True,default=0) last_modified = models.DateField(("Date"), default=datetime.date.today) -
Creating a templatetag to check users
Creating a templatetag for checking is requested user is in group or not, but it is not working. I have a models class called Team, in that class there is members, and i want to check if the user is part of the team. Models.py class Team(models.Model): team_admin = models.ForeignKey(Profile, on_delete=CASCADE) team_name = models.CharField(max_length=55, unique=True, blank=True) members = models.ManyToManyField(Profile, related_name='teams') slug = models.SlugField(max_length=500, unique=True, blank=True) description = models.TextField(default='Team description') date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.team_name) super(Team, self).save(*args, **kwargs) def get_url(self): return reverse('projects', kwargs={ 'slug':self.slug }) def __str__(self): return self.team_name auth_extras.py from django import template from django.contrib.auth.models import Group register = template.Library() @register.filter(name='has_group') def has_group(user, group_name): group = Group.objects.get(name=group_name) return True if group in user.groups.all() else False {% if request.user|has_group:"team" %} No matter what i try, if its team, team.members, members, nothing. always get; Group matching query does not exist. -
Is Python and python3 in Linux has different pip?
I installed Django on my Ubuntu 21.04 Software but when I use: python manage.py runserver I get an error massage : No module named “Django” But when I use : python3 manage.py runserve It works fine but my python —-version is 3.10.1 and python3 —version is 3.9.x So what is the error and how I can run it with python only not python3 -
Add tests for django filters
I'm using factory-boy to add tests in Django, and I have a filter : class filter(django_filters.FilterSet): class Meta: model = modelname fields = ["name","id","price"] and I wanna add tests for that filter. how should I write the test for that? -
Uploading images in django
I have being using django for sometime but recently noticed this. Before now I thought images in django, by default, gets uploaded in the path specified in STATIC_URL but I just saw that the bahaviour is diffrent in my app. I have this set up in settings.py: class BlogPost(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) category = models.CharField(max_length=50, choices=Categories.choices, default=Categories.medications) title = models.CharField(max_length=50) slug = models.SlugField() image = ResizedImageField(upload_to='images/blog/', null=True, blank=True) introduction = models.CharField(max_length=255) body = models.TextField() settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static',), os.path.join(BASE_DIR, 'frontend/build/static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') The static, staticfiles, and media are within the root directory. In my django app, if media directory isn't present the images get uploaded in static directory. However, when both static and media directorie are present preference is given to the media directory (the images get uploaded in media directory). Did I make a mistake somewhere? -
How to avoid no such table error Django db
Using django python, I come across this error whenever I want to clone the repository, and so I assume its whenever it creates a new database (the database is on .gitignore). I know its an issue regarding the models, but I have no idea how to fix it. Its not an issue for me as of right now, but will be if I move to production. Traceback (most recent call last): File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 416, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: blogger_postcategory The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 446, in check for pattern in self.url_patterns: File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/urls/resolvers.py", line … -
Images in django not showing up in react
This is an application in which I'm using django backend and react frontend. The images display in react when I keep react and django separate and communicate simply with the APIs. However, I want to deploy both the frontend and backend together. I'm trying to use django re_path to redirect any url that does't match with the urls specifiled in django urls.py. Whenever I do this the images from react and django stop displaying. Both django and react lose track of the path of the images. project structure >backend ... settings.py urls.py >blog ... urls.py serializers.py views.py >frontend ... build src package.json manage.py >static urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('djoser.urls')), path('api/', include('djoser.urls.jwt')), path('api/', include('accounts.urls')), path('summernote/',include('django_summernote.urls')), path('api/blog/', include('blog.urls')), re_path('*', TemplateView.as_view(template_name='index.html')), ] settings.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'frontend/build') ], 'APP_DIRS': True, }, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static',), os.path.join(BASE_DIR, 'frontend/build/static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Also, whenever I use re_path to redirect unmatched urls from django to react the images in react such as the logo stop displaying but withouy setting re_path all the images in react, … -
Django - How to add annotation to queryset for request.user
I want to add new field to queryset (by annotate()) according to request.user. I have following models: class Tweet(models.Model): ... class Like(models.Model): tweet = models.ForeignKey(Tweet, related_names='likes') user = models.ForeignKey(AUTH_USER_MODEL, related_name='my_likes') type = models.CharField( choices=( ('like', _"Like"), ('dislike', "Dislike") ), ... ) Now I want to execute following query: tweets = Tweet.objects.all().annotate(user_reaction=some_method(request.user)) And I want to this annotated_field(user_reaction), reaction of user to the tweet. user_reaction has 3 states: 1- Like 2- Dislike 3- None (user hasn't like/dislike the tweet) I want to have something like tweets[10].user_reaction, and after that get one of 3 states that came before. (just like, dislkie or None) How can I do this? thanks. -
What would be the best design to manage multiple markets
I have one project, frontend used as Angular and backend used as Django. The project was used for multiple markets, for example, Japan, Mexico, Canada, etc. The database data columns vary for all markets and also the feature is changed for all the markets. For this reason, we have kept the code in different branches like master_uk, master_jp etc. Here is the problem: if I have any issues with the base code. I need to fix all the branches and test all the markets. If I manage one code for all the markets and configurable(Need to think). if I move any change to one market that might be affecting all other markets. What would be the best design to manage multiple markets? -
I get an invalid hosts error when installing ssl certification on django web app [closed]
recently I’ve launched a web app and I went through the process of installing an ssl certificate through the command prompt. While the site is shown as secure, I get a constant invalid hosts error despite including the domain name and IP address in the allowed hosts list in settings.py. Can anyone who has gone through this before guide me on what to do? Thank you! -
Repository does not have a Release file. for Ubuntu 16.04
Here in my dev server i am upgrading from python 2.7 to python 3.7 when using the command python --version 2.7.14 python3 --verison 3.5.2 python3.7 --version 3.7.10 and when running the command sudo apt-get update this is what i am getting Err:15 https://dl.bintray.com/rabbitmq/debian xenial/main amd64 Packages 502 Bad Gateway Fetched 325 kB in 4s (78.1 kB/s) Reading package lists... Done W: The repository 'https://dl.bintray.com/rabbitmq/debian xenial Release' does not have a Release file. N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use. N: See apt-secure(8) manpage for repository creation and user configuration details. E: Failed to fetch https://dl.bintray.com/rabbitmq/debian/dists/xenial/main/binary-amd64/Packages 502 Bad Gateway E: Some index files failed to download. They have been ignored, or old ones used instead. here is Output of cat /etc/apt/sources.list ## Note, this file is written by cloud-init on first boot of an instance ## modifications made here will not survive a re-bundle. ## if you wish to make changes you can: ## a.) add 'apt_preserve_sources_list: true' to /etc/cloud/cloud.cfg ## or do the same in user-data ## b.) add sources in /etc/apt/sources.list.d ## c.) make changes to template file /etc/cloud/templates/sources.list.tmpl # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to # newer versions … -
How does one include static information as part of a Django Model?
I have spent the last few hours trying to create something which I thought would have been very trivial, but alas, it was not… I am creating a Django model that asks the user a random question from a list: prompts. Inside my models.py file I have: from django.db import models from .prompts import prompts class Entry(models.Model): question = str(random.choice(prompts)) answer = models.CharField(max_length=240) I'm using the generic CreateView to create the a form, and my views.py contains the following: from django.views.generic.edit import CreateView from .models import Entry class NewEntry(CreateView): model = Entry success_url = reverse_lazy('detail') fields = ['question', 'answer'] Everything migrates correctly, but when I navigate to the relevant page in the browser, Django complains: FieldError at /create/ | Unknown field(s) (question) specified for Entry I understand that question is not a field per se, but I do need it to be saved as part of the Entry instance so that in the future I may read both the answer and the question that was asked at the time. Naturally, I also need it to display in a template as part of the form which is produced by CreateView. Setting the question to be a CharField that is uneditable also … -
Django with pandas
I want display dataframe with info from pandas df.info() this display to output in the command prompt but in html display None !! Views.py my_file = pd.read_csv(filename, engine='python') data = pd.DataFrame(data=my_file) mydict = { "data": data.to_html(), "dinfo": data.info(), } <div><h6 class="major">Data </h6>{{data|safe}}</div> <div><h6 class="major">Data Info:</h6>{{dinfo|safe}}</div> -
Django-AWS S3, unable to delete bucket objects
I have a Django project with MySQL storage and media objects (images) are being stored in AWS S3 simple storage. Admin can upload images through admin panel and its being displayed in website too. When admin delete objects , it gets deleted in MySQL but it's associated images persists in S3 bucket. SETTINGS.PY AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.me-south-1.amazonaws.com" AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'news.storage_backends.MediaStorage' STORAGE_BACKENDS.PY from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class MediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' file_overwrite = False I am user details as attached, -
How to implement Djnago-internation into models
I need to make dropdownlist using currency name of all countries. I found documents which are not mentioned how to use properly. international.models.currencies This is atuple of tuples compatible with choices argument passed to Django’s model/form fields. The values are ISO 4217 3-letter currency codes, and display values are the same codes with full currency names. For example: ('USD', 'USD - United States Dollar') This tuple is used as choices argument for the ChoicesField in the currency form. here i have given link: https://pypi.org/project/django-international/ Please, If anyone knows how to do just do reply,.. -
Show number of items in Django in list view
I am trying to show the number of each category in Leads. But i am unable to show it. Appriciate your help. I am learning django and python. Tried many opiton, but failed. Below is my code. Model: class Leads(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) age = models.IntegerField(default=0) orginasation = models.ForeignKey(UserProfile, on_delete=models.CASCADE) agent = models.ForeignKey("Agent",null=True, blank= True ,on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="leads", on_delete= models.SET_NULL, null=True, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" class Category(models.Model): name = models.CharField(max_length=30,) # New, Contact, Converted, Unconverted orginasation = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.name View: class CategoryListView(LoginRequiredMixin, generic.ListView): template_name = "leads/category_list.html" context_object_name = "category_list" def get_queryset(self, **kwargs): user = self.request.user #initial query set for entire organisation if user.is_organisor: queryset = models.Category.objects.filter(orginasation=user.userprofile) else: queryset = models.Category.objects.filter(orginasation=user.agent.orginasation) # count = models.Leads.objects.filter(category = 3).count() return queryset template {% for category in category_list %} <tr> <td>{{category.name}}/td> <td>{{category.count}}</td> </tr> {% endfor %} -
Django ORM Optimal solution for bulk stock data store?
i am working on django project in my project i am have created models product,branch,stock i and one of database server there to i am fetch 4 lack around records of stock data and storing in my project database but problem is i am storing through orm its taking 50 min to storing 4 lac records is there best solution to reduce the time. you can see below model class which i am storing stock data. thankyou i advance. class Stock(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=True, blank=True) quantity = models.PositiveIntegerField(default=1) updated_on = models.DateTimeField(blank=True, null=True) created = models.DateTimeField(editable=False,blank=True, null=True) updated = models.DateTimeField(editable=False,blank=True, null=True) -
Uploading a `FileField` to a specific folder in Django Python
How can I use the django FileField to upload the file to the specified folder directly without going through the admin panel or using the form for normal user? -
How to detect and get the changes from past 24 hours in database using django?
I am having around 5000 user records and I also have an external intercom API for posting user data. Every time I run that API it takes hours to complete because it has to compare every user again and again to insert the created or updated data in the database. so, I wanted to send the latest created or updated data from the database to an external API like an intercom. -
How to get variables between the curly brackets in django template in django views?
I have django template file. Now i want to get all the variables list that are between curly brackets. I think it is possible with the regular expressions. And i read about regular expressions. But there is no function i found to be helpful. template code snippet: <tr><td> Dear Candidate,<br/> Welcome to Creative Talent Management!<br/> We have created an account for you. Here are your details:<br/> Name:{{name}}<br/> Email:{{email}}<br/> Organization:{{organization}}<br/> Password:{{password}}<br/> </td></tr> I want to get name,email,organization,password in my python function. -
django - Unable to set delimiter in raw sql (MySQL)
I want to define a stored procedure by a migration. Before this I'm trying to set delimiter but getting django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER $$' at line 1") Code: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('...', '...'), ] operations = [ migrations.RunSQL("DELIMITER $$"), # ... migrations.RunSQL("DELIMITER ;"), ] I've found information about DELIMITER is a client keyword which might not be supported by specific tool but what is the right way in django?