Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
update two models different in the same template with only one button "submit" using class based view(UpdateView)
i want to update two different models with one button.using class based view (UpdateView). for example... class AboutMe(models.Model): adress = models.CharField(max_length=13, null=True) phone_number = models.CharField(max_length=13, null=True) class MoreAboutMe(models.Model): MySecondAdress = models.CharField(max_length=100) -
django - keras - aws elastic beanstalk - Updating data for deployed app
Background I am on a mac OS X Yosemite 10.10.5. There does not seem to be any literature on here referring to this specific problem with the measure of intricacies I am finding. This involves the simple deployment of a django application. pythonanywhere will deploy it, but is incredibly slow. I have a large model (.hd5) file generated from a deep net in keras. This is about 1.5 GB in size. My entire project is about 1.77 GB. I have the entire project working perfectly, with generalized code (e.g., using os.path.join instead of relative references) and everything kosher with the django documentation. This is what fuels my search engine in my application, without this, the entire site is not worth deploying, as all d3.js charts populate from its data returned. This same problem occured on pythonanywhere.com, after purchasing their extended package to store 5GB, the site ran too slow to even make it worth it. Granted, this was a flask prototype and I have ported all code to django now. Problem I have gone throughthis entire tutorial, from front to back, with military precision and I have no had errors running locally. This is after running python startproject dwsite. I … -
Django: putting more context in get_context_data in class-based-view
I do know that to put more context in a listview in django, we can just something like: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) b = 9 context['num'] = b return context and with that, we can use num in our template file. But let's say I want to variables to be placed in the context, what do I do? b = 9 a = 10 context['a', 'b'] = a, b and then I refered to this in my html template by directly calling {{a}} or {{b}}, no errors shows up, but nothing shows up either. I think I have some misconception about a basic dictionary, and django adds confusion to it because it seems like you can't use () or [] inside of {{}}, by the way can someone answer why we can't use () or [] inside of the html code inside of {{}}? -
Django tests.py django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username
The question asked before but the error was having the same username in the database. In my case database is totally empty ., here is the test case: def create_django_contrib_auth_models_user(**kwargs): defaults = {} defaults["username"] = "adminadmin" defaults["email"] = "test@testus.com" defaults["password"] = "testpass" defaults.update(**kwargs) return User.objects.create(**defaults) when I run python manage.py tests i get this error as and it causes most of the other tests to fail, django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username -
How do i host python2 and python3 applications on the same apache2 server?
i' ve 2 django applications. One of them is using python2.7 and the other is python3.4 . For the python2.7 libapache2-mod-wsgi should be installed, but for the other application libapache2-mod-wsgi-py3 is required. It seems these 2 packages can' t be installed on the same system. What would be the best way to host this 2 applications? Debian: 8.6 Apache: 2.4.10-10+deb8u7 App1: python==2.7, Django==1.11.16 App2: python==3.4, Django==2.0.9 . -
404 errors on static assets in Django/Vue app
I was trying to follow this article to deploy a Django/Vue app to heroku. The steps outlined are to: run npm build to create the /dist directory with built files to the TEMPLATES = [...] section of settings.py, add 'DIRS':[os.path.join(BASE_DIR, 'dist')], add STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'dist/static')], (also in settings.py) edit the django urls.py file to include this line: url(r'^$', TemplateView.as_view(template_name='index.html')), I've done all of those things at this point, here is my sanitized settings.py file: """ Django settings for bad_fortune_cookie project. Generated by 'django-admin startproject' using Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os import dj_database_url #from whitenoise.django import DjangoWhiteNoise from rest_framework import * # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com','localhost'] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'bad_fortune_cookie', #'fortunes' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bad_fortune_cookie.urls' TEMPLATES = … -
Advantages of implementing a navbar.html in django templates?
I want to develop a best practice for placing a navbar in all my Django web apps. At the moment I am placing the navbar in base.html. And then extending base.html on all other templates. I have seen that some people create a navbar.html and then include that in base.html. Is there a best practice here? Are there any advantages to using navbar.html? -
Django Shop - filter products by brands and by price and other attributes in forms
I try to create an online store, and I cannot filter at the same time brands and prices from and to. I have one form. Where there are fields (Brands, min_cena and max_cena) in the template I have two columns on the left, as on all sites of stores in one column, brands in another column, two fields where you can set the price from and to. Correspondingly, I have two forms with the het method and two buttons that transmit parameters. If add the output of brands and price fields under one button to submit, then everything works. But it looks ugly, and individually I give it either to a request or to prices or brands. forms class BrandForms(forms.Form): brand = forms.ModelMultipleChoiceField(queryset=Vendor.objects.none(), widget=forms.CheckboxSelectMultiple(), required=False) min_price = forms.IntegerField(label='от', required=False) max_price = forms.IntegerField(label='до', required=False) views filter_brand = BrandForms(request.GET) if filter_brand.is_valid(): if filter_brand.cleaned_data['brand']: print(filter_brand.cleaned_data['brand']) list_pro = Product.objects.filter(category__in=Category.objects.get(id=category.id)\ .get_descendants(include_self=True)) \ .annotate(min_price=Min('prices__price'))\ .filter(vendor__in=filter_brand.cleaned_data['brand']) products_list = helpers.pg_records(request, list_pro, 12) if filter_brand.is_valid(): if filter_brand.cleaned_data['min_price']: list_pro = list_pro.filter(prices__price__gte=filter_brand.cleaned_data['min_price']) products_list = helpers.pg_records(request, list_pro, 12) template {% if vendors.count >= 10 and vendors%} <div class="shop-sidebar mb-35"> <h4 class="title" data-spy="scroll" data-target="#brand_liste">Бренды</h4> <form id="form1" action="." method="get"> <div class="input-group"> <input id="brand_list_input" type="text" class="form-control" placeholder="Поиск бренда" aria-label="Recipient's username" aria-describedby="basic-addon2"> <div class="input-group-append"> <button class="px-3" … -
How to create a jsfiddle like view in Django?
I am trying to do a similar form like jsfiddle. My model contained 4 fields (Html, CSS, JS and Result). Currently I simply use the standard detail view to show this model. And every field is text aread. I could write the CSS to a static folder and include the CSS in the template file, but obviously it is not dynamic. I was thinking to create a new widget, but not quite sure it is correct approach. Do you have any idea and give me the direction? Thanks BY -
How to fix: Django error: no such table: main.classroom_student__old
I am following this tutorial for learning how to create a Django (v2.0.1) app with multiple user types (teachers and students in this case). I cloned the associated code from the Github Repository, migrated the pre-made migrations using: python3 manage.py migrate and ran the site on localhost using python3 manage.py runserver The site works almost perfectly (Teacher sign up, login, quiz creation, and student log in are all in order). However, the student Signup fails with the following error: OperationalError at /accounts/signup/student/ no such table: main.classroom_student__old With the traceback pointing eventually to the file django_school/classroom/forms.py, line 39: student.interests.add(*self.cleaned_data.get('interests')) That line comes from the definition of the following class in that forms.py file: class StudentSignUpForm(UserCreationForm): interests = forms.ModelMultipleChoiceField( queryset=Subject.objects.all(), widget=forms.CheckboxSelectMultiple, required=True ) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_student = True user.save() student = Student.objects.create(user=user) student.interests.add(*self.cleaned_data.get('interests')) return user -------What I have tried-------------------------------------- Following answers to the many similar questions on this site, I assumed it was a migration issue so I tried running python manage.py migrate --run-syncdb Operations to perform: Synchronize unmigrated apps: crispy_forms, humanize, messages, staticfiles Apply all migrations: auth, classroom, contenttypes, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: No … -
Django. Media url not found
I have a django project based on django 1.11. I uploaded media files and try to get them but instead I get nothong. I read documentation and did exactly as it said. Also I checked 'media' foleder permissions. settings.py: MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('myapp.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
AttributeError: 'NoneType' object has no attribute 'split', Sending post request with ajax to django
I've wrote a method in my views.py as a api for user login. (using django 2.1) it's completely working with POSTMAN, but when I try to use ajax to send request to this api, it's kind of work but instead of returning jsonresponse with proper status code, I have this strange error in my server console. This is Error: [23/Dec/2018 21:40:46] "POST /api/login/ HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 56813) Traceback (most recent call last): File "c:\python37\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "c:\python37\Lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "c:\python37\Lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "c:\python37\Lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "c:\python37\Lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "c:\python37\Lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "c:\python37\Lib\socketserver.py", line 796, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted b y the software in your host machine During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\python37\Lib\wsgiref\handlers.py", line 141, in run self.handle_error() File "C:\Users\crash\Envs\user_auth\lib\site-packages\django\core\servers\base http.py", line 98, in handle_error super().handle_error() File "c:\python37\Lib\wsgiref\handlers.py", line 368, in handle_error self.finish_response() File "c:\python37\Lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "c:\python37\Lib\wsgiref\handlers.py", line 274, in write … -
How to dedicate a text box value in a variable
How to dedicate a textbox value in a variable then save/insert it in the model after making the model in Django? -
Django on AWS Beanstalk errors when using Postgres
I have an Django application using RDS Postgres on AWS Beanstalk. The Beanstalk environment does not use the default RDS setup. I have a separate RDS instance of Postgres running. In my settings file I have the below for my database dictionary: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } When I visit the environment's URL I get a 500 error. Below are the error_logs for one visit. [Sun Dec 23 18:43:24.116897 2018] [:error] [pid 1881] [remote 172.31.30.131:0] mod_wsgi (pid=1881): Target WSGI script '/opt/python/current/app/my_app/wsgi.py' cannot be loaded as Python module. [Sun Dec 23 18:43:24.117094 2018] [:error] [pid 1881] [remote 172.31.30.131:0] mod_wsgi (pid=1881): Exception occurred processing WSGI script '/opt/python/current/app/my_app/wsgi.py'. [Sun Dec 23 18:43:24.117230 2018] [:error] [pid 1881] [remote 172.31.30.131:0] Traceback (most recent call last): [Sun Dec 23 18:43:24.117313 2018] [:error] [pid 1881] [remote 172.31.30.131:0] File "/opt/python/current/app/my_app/wsgi.py", line 16, in <module> [Sun Dec 23 18:43:24.117458 2018] [:error] [pid 1881] [remote 172.31.30.131:0] application = get_wsgi_application() [Sun Dec 23 18:43:24.117553 2018] [:error] [pid 1881] [remote 172.31.30.131:0] File "/opt/python/run/venv/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Sun Dec 23 18:43:24.117668 2018] [:error] [pid 1881] [remote 172.31.30.131:0] django.setup(set_prefix=False) [Sun Dec 23 18:43:24.117757 2018] [:error] [pid 1881] [remote 172.31.30.131:0] … -
DjangoDisallowedHost in AWS ECS
I'm trying to deploy a sample django application into was ecs using fargate. I don't have a domain yet and I read that you can append your public ip to ALLOWED_HOSTS. So I changed my configuration to add it using this link as a guide ALLOWED_HOSTS = ['localhost', '127.0.0.1', '.example.com'] PUBLIC_IP = None try: response = requests.get('http://169.254.169.254/latest/meta-data/public-ipv4', timeout=3) print('Response') PUBLIC_IP = response.text ALLOWED_HOSTS += [PUBLIC_IP] except requests.exceptions.RequestException as e: print('Exception on getting public ip ', e) print(ALLOWED_HOSTS) Unfortunately it doesn't work for me, probably because I'm not using an ec2 instance. Can somebody show me how to add my public ip? I'm using daphne, with the following command daphne -b 0.0.0.0 -p 80 my_project.asgi:application I don't even get these print statements between my logs, in ecs task. But I get the daphne logs -
SQLAchemy and Django
Is there a some way to do the same thing like prefetch_related in DjangoORM in SQLAlchemy? I have models like this: class User(...): regions = models.ManyToMany(Region) name = models.CharField(...) class Region(...): title = models.CharField(...) And I have the same classes for sql alchemy. And I want to rewrite the code in sql alchemy: name = 'Lucas' users = User.objects.filter(name=name).prefetch_related('regions') -
Struggling with subject to learn(django,game and app development, reverse engineering)
I have been struggling to find a subject to deep study.. the subjects(more like choices)are : django, unity game programming, reverse engineering in assembly and java app developing. I would be happy if someone could light me up at one or more of the subjects from his own experience or recommending me about a new subject of his own(Note:Telling me to try and find out by myself wont help..) I have knowledge in python,java,C# and little bit of html\css I have tried unity, java app developing in android studio and django a little bit.. but every time i started a project i didn't acutely finish it Heading -
How can I run an app script python in django (hosted in a2hosting)?
Im just setup my first django project on hosted server (a2hosting), now I want to run on the web application my python script (calculating some things and then redirects to other url).. but Im not sure how I setting it up on my django server ? can someone help please? -
How to connect user and groups when user registration in django
I m trying to create a user management app with django. When creating a new user, it includes all data to corresponding fields, except the groups field. I use django auth models and generic base view So far this is my code forms.py class UserRegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'password', 'confirm_password', 'email', 'first_name', 'last_name', 'groups'] views.py class RegisterFormView(LoginRequiredMixin, View): login_url = '/user/login' user_class = UserRegisterForm profile_class = ProfileForm template_name = 'user/registration_form.html' # Display blank form def get(self, request): form = self.user_class(None) form_1 = self.profile_class(None) context = { 'form': form, 'form_1': form_1 } return render(request, self.template_name, context) # Process form data def post(self, request): form = self.user_class(request.POST) form_1 = self.profile_class(request.POST, request.FILES) context = { 'form': form, 'form_1': form_1 } if form.is_valid() and form_1.is_valid(): user = form.save(commit=False) # Clean data username = form.cleaned_data['username'] password = form.cleaned_data['password'] confirm_password = form.cleaned_data["confirm_password"] if password != confirm_password: raise form.ValidationError( "password and confirm_password does not match" ) user.set_password(password) user.save() profile = form_1.save(commit=False) form_1.cleaned_data['image'] profile.user = user profile.save() # Returns user user = authenticate(username=username, password=password) if user is not None: if user.is_active: return redirect('user:accounts') return render(request, self.template_name, context) The output must be "A_Group", but it outputs "auth.Group.None" -
Django-taggit query objects if the tag field contains 2 or more elements?
I'm wondering how to query multiple tags through taggit. I'm currently using django-taggit. I'm using pizza as a placeholder name. How can I filter in a way that only returns objects that contain 2 or more tags? For example, if I wanted to query different types of pizzas: >>> Pizza.objects.create(name='Pizza 1', tags=[pepperoni]) >>> Pizza.objects.create(name='Pizza 2', tags=[pepperoni, chicken, onions]) >>> Pizza.objects.create(name='Pizza 3', tags=[pepperoni, sausage, cheese, onions]) >>> Pizza.objects.filter(tags__contains=['pepperoni', 'onions']) <QuerySet [<Pizza: Pizza 2>, <Pizza: Pizza 3> ]> Here is the current implementation of django-taggit. It queries the tags separately, but often times my objects will share 1 tag, but not 2 tags. I would like to query if 2 or more tags are present. models.py class UUIDTaggedItem(GenericUUIDTaggedItemBase, TaggedItemBase): class Meta: verbose_name = _("Tag") verbose_name_plural = _("Tags") class Pizza(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) tags = TaggableManager(blank=True, through=UUIDTaggedItem) filters.py class TagsFilter(CharFilter): def filter(self, qs, value): if value: tags = [tag.strip() for tag in value.split(',')] qs = qs.filter(tags__name__in=tags).distinct() return qs class PizzaFilter(filterset.FilterSet): tags = TagsFilter(field_name="tags", lookup_expr='icontains') class Meta: model = Pizza I'm also using postgres as my db, I've considered using ArrayField, but I've read a stack overflow questions that don't suggest using ArrayField for tags. -
How to get a list of all tags from Tagulous in Django Graphene
This is my model: class FeedSource(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) feed = models.ForeignKey(Feed, on_delete=models.CASCADE) #FIXME: Deletion title = models.CharField(max_length=200) show_on_frontpage = models.BooleanField(default=True) tags = TagField() def __str__(self): return self.title class Meta: ordering = ["title"] unique_together = (("user", "feed")) And this is my attempt to get all tags in schema.py: class TagType(DjangoObjectType): class Meta: model = tagulous.models.TagModel # model = FeedSource interfaces = (graphene.relay.Node,) class Query(graphene.ObjectType): all_tags = graphene.List(TagType, username=graphene.String(required=True)) def resolve_all_tags(self, info, **kwargs): tags = FeedSource.tags.tag_model.objects.all() return tags In graphiql I get the error: Expected value of type \"TagType\" but got: Tagulous_FeedSource_tags." How can I set the model so that GraphQL will work and I can retrieve a list of all my tags? -
I would like to annotate new column 'is_like' in Django
i use this queryset <Queryset[<UsePoint:a>,]> <name:a, like_users_count:3> my code: user_exists = User.objects.filter( pk=self.request.user.pk, pk__in=OuterRef('like_users'), ) queryset = queryset.annotate(is_like=Exists(user_exists)) i think it return one queryset like this <Queryset[<UsePoint:a>,]> <name:a, is_like:true, like_users_count:3> but It returns two queryset <Queryset[<UsePoint:a>,<UsePoint:a>]> <name:a, is_like:false, like_users_count:2> <name:a, is_like:true, like_users_count:1> how can i distinct these result? -
Could the directus app be used in a django stack as a CMS
I am developing a web application in django and react but would like to use directus as a cms. I already have a mysql database and RESTful api set up and working so I was wondering if I could use the directus application as an application within django to manage and update content? if not what would be the correct way to connect directus to my application? or should I stick with a cms built for integration into django projects? -
Could Someone help me with the configuration of django-smart-selects with python3
Could someone please help me with a working configuration of urls.py, forms.py, views.py and a template that use django-smart-selects because mine don't seem to work -
Python - Sanitize keys in Sentry logging handler (django)
I'm adding a Sentry logging handler to my Django project. I want to customise the sentry handler by adding sanitize keys, and two processors: raven.processors.SanitizePasswordsProcessor, raven.processors.SanitizeKeysProcessor. Is there a way to do it in the logging configuration without writing a new handler class, wrapping the raven.contrib.django.raven_compat.handlers.SentryHandler class with the parameters I want? This is my logging config: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'x': { #'format': '[%(asctime)s #%(process)d] %(levelname)s: %(message)s' 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s - {%(pathname)s:%(lineno)d}' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'x' }, 'sentry': { 'level': 'ERROR', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler' } }, 'loggers': { 'django': { 'level': 'INFO', 'handlers': ['console', 'sentry'], 'propagate': True }, } Thank you