Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a function that identifiies object type and passes form depending on what type the object is
I have a model named product, and depending on the type of product I would like to pass a form. So, for example, if the product type is "Clothing", then render a form to select a size (S, M, L, etc...) I've tried creating a view that passes the product to a template, and then made a function within the view called is_clothing that says product type is clothing. # models.py PRODUCT_TYPE = [ ('C', 'Clothing'), ('A', 'Accessory'), ('F', 'Furniture'), ] class Product(models.Model): ... type = models.Charfield(blank=True, choices=PRODUCT_TYPE) # views.py def product_view(request, slug): productvariant = get_object_or_404(ProductVariants, slug=slug) form = ProductSizeForm # Function that defines whether product type is clothing def is_clothing(): product.type == "Clothing" context = { 'product' : productvariant, 'form' : form } return render(request, "products/product-page.html", context) <!--TEMPLATE--> {% if product.is_clothing %} {{ form }} {% endif %} As I said I was hoping to render the sizes form if the product type is clothing, but I'm not getting any results. Any ideas? -
Facing trouble in running python manage.py runserver
I am trying to run python manage.py runserver and till today I never faced any issues. Whenever I run python manage.py runserver I get this- $ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). August 11, 2019 - 05:34:42 Django version 2.1.5, using settings 'try_django.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f0b20e6d6a8> Traceback (most recent call last): File "/home/user/anaconda3/lib/python3.7/site-packages/django/utils/module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user/anaconda3/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/home/user/anaconda3/lib/python3.7/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/home/user/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/user/Dev/try_django_new/src/try_django/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/user/anaconda3/lib/python3.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/home/user/anaconda3/lib/python3.7/site-packages/django/core/handlers/wsgi.py", … -
Add range and ><= operators to django form
I am building enterprise software which someone can use to input order data from a customer. Sometimes customers order something with length 1000+ or will order something within a range of 400-600 for example. How can I display these options in a dynamic form which inputs an integer into a model? Will my model have to have max_length min_length, max_width, min_width etc or is there a better way? I've considered creating non-required fields and dynamically displaying the form depending on a dropdown menu choice near every dimension with (greater than, equal to, less than). This will make me create around 6 new fields for a basic l/w/h input. For example: If someone wants a range they can click on the side dropdown near the dimension and select range, which will then show a new input box which submits data to max_DIMENSION. Or when a user chooses > then the database saves that field as greater than. I expect to be input a range with 2 values, or a >/=/< with a single value. -
Cannot Import Name LoginView
I am trying to create a modal form in my django project. I am trying to use bootstrap modal forms and I am following an example: https://pypi.org/project/django-bootstrap-modal-forms/ When I import in views.py: from bootstrap_modal_forms.generic import BSModalCreateView I get an error "cannot import name LoginView" - but I'm confused because I do not have LoginView anywhere in my project. Why is this happening? This is my first time trying to use Class Based Views. I know this isn't a lot of detail, but I am completely confused here. -
Set a secret key with command line in Django for saleor installation on windows
I'm trying to install saleor on Windows, in the SECRET_KEY part throws an error saying that my SECRET_KEY cannot be empty, I suppose it must be entered by commands. What command is used in Windows to set a SECRET_KEY in Django and then continue to the next step of installing saleor? -
how to open a database created with docker in django
I have a question about how to open a database created with docker using https://github.com/cookiecutter/cookiecutter in pgAdmin. In the folder /home/lyon/Documentos/tienda/.envs/.local there is a file called .postgres and contains the following data: # PostgreSQL # ------------------------------------------------------------------------------ POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_DB=tienda POSTGRES_USER=debug POSTGRES_PASSWORD=debug but the connection is useless :( How can I see my database? Thank you -
How to run a combination of query and filter in elasticsearch?
I am experimenting using elasticsearch in a dummy project in django. I am attempting to make a search page where the user may provide a title, summary and a score to search for. The search should match all the information given by the user, but if the user does not provide any info about something, this should be skipped. I am running the following code to search for all the values. s = Search().using(client).query("match", title=title_value)\ .query("match", summary=summary_value)\ .filter('range', score={'gt': scorefrom_value, 'lte': scoreto_value}) When I have a value for all the fields then the search works correctly, but if for example I do not provide a value for the summary_value, although I am expecting the search to continue searching for the rest of the values, the result is that it comes up with nothing as a result. Is there some value that the fields should have by default in case the user does not provide a value? Or how should I approach this? -
Problem in saving formset in django Updateview
I am new in Django and Stackoverflow, so please accept my apology if my codes is not standard. I try to create a blogging website. Users can create and update posts and each post can have one or more categories or no category. I use form for Post and Formset for Category. However, in Updateview for some reason I couldnt save the formset!!!! models.py class Post(models.Model): title = models.CharField(max_length=128) text = models.TextField(blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): name = models.CharField(max_length=128, unique=True) description = models.TextField(blank=True) posts = models.ManyToManyField(Post, blank=True,related_name='categories') class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name forms.py class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'text', 'published_date'] CATEGORY_CHOICES = [('', 'Choose from the list')] for c in Category.objects.all(): CATEGORY_CHOICES.append((c, c)) class CategoryUpdateForm(forms.ModelForm): class Meta: model = Category fields = ['name'] labels = {'name': 'Category'} help_texts = {'name': 'Choose category for your post'} widgets = { 'name': forms.Select(choices=CATEGORY_CHOICES) } CategoryFormset = forms.modelformset_factory(Category, form=CategoryUpdateForm, extra=1, max_num=3, can_delete=True) views.py class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post template_name = 'blogging/post_update.html' form_class = PostUpdateForm formset_class = CategoryFormset def form_valid(self, form): form.instance.author … -
How to make a button by clicking on which the font will change
Я хочу , добавить такие кнопки в мою admin panel , чтобы по нажатию на такую кнопку я мог писать более крупным шрифтом , или мелким . Также хотелось бы добовлять изображения. And you need to add a button with which you can add images. enter image description here Can you please drop the code, or where you can see it, or maybe there is a separate application. admin.py from .models import Articles, CommentModel admin.site.site_header = 'Admin Dashboard' class ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'date') prepopulated_fields = {'slug': ('title',)} list_filter = ('date',) readonly_fileds = ('body_preview',) admin.site.register(Articles,ArticleAdmin) models.py class Articles(models.Model): title = models.CharField(max_length= 200) post = models.TextField() slug = models.SlugField(unique=True, verbose_name='URL') date = models.DateTimeField() img = models.ImageField(upload_to='', default="default_value",verbose_name='Каритинка 260х180') tags = TaggableManager() article_like = models.IntegerField(default='0') article_dislike = models.IntegerField(default='0') view = models.IntegerField(default='0') datesArticle = models.DateTimeField(auto_now=True) class Meta: ordering = ['-datesArticle'] def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return "/news/%s/" % (self.slug) -
Can you create instances of two foreign keys referencing the same model in one model?
I'm trying to create two instances of a model class called Team. I want to create two fields stored in my GameId Model called home and visitor. These two foreign keys are referenced from the same model called Team. Should I use a foreign key or many to many field relationship? Background of models: One team can have many gameids One gameid should have 2 teams class GameId(models.Model): week = models.CharField(max_length = 100) day = models.CharField(max_length = 100) home = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='home') visitor = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='visitor') gameid = models.CharField(max_length = 100, blank=True) slug = models.SlugField(max_length=100, unique=True, blank=True) -
TypeError: got an unexpected keyword argument 'model' (Django)
I'm creating a data migration for the purpose of instantiating several Mineral objects for the database. Upon running python manage.py migrate in the console I get the error: TypeError: Mineral() got an unexpected keyword argument 'model'. I can't find anything resembling this keyword that Django is raising. What is causing this error which is preventing model instances from being created? #models.py from django.db import models # Create your models here. class Mineral(models.Model): name = models.CharField(unique=True, max_length=60, null="") image_filename = models.CharField(max_length=65, null="") image_caption = models.CharField(max_length=410, null="") category = models.CharField(max_length=50, null="") formula = models.CharField(max_length=280, null="") strunz_classification = models.CharField(max_length=110, null="") color = models.CharField(max_length=195, null="") crystal_system = models.CharField(max_length=130, null="") unit_cell = models.CharField(max_length=140, null="") crystal_symmetry = models.CharField(max_length=130, null="") cleavage = models.CharField(max_length=170, null="") mohs_scale_hardness = models.CharField(max_length=70, null="") luster = models.CharField(max_length=75, null="") streak = models.CharField(max_length=60, null="") diaphaneity = models.CharField(max_length=80, null="") optical_properties = models.CharField(max_length=85, null="") refractive_index = models.CharField(max_length=125, null="") crystal_habit = models.CharField(max_length=240, null="") specific_gravity = models.CharField(max_length=70, null="") group = models.CharField(max_length=20, null="") def __str__(self): return self.name # retrieve_json.py import json def pull_json(file): with open(file, 'r') as json_file: data = json.load(json_file) return data from django.db import migrations import os.path from ..data.retrieve_json import pull_json def load_mineral_data(apps, schema_editor): Mineral = apps.get_model('minerals', 'Mineral') mineral_data = pull_json(os.path.abspath('minerals/data/minerals.json')) for m in mineral_data: Mineral.objects.create(**m) class Migration(migrations.Migration): … -
Python "bitwise or" on array
I have an array of Django querysets. Django querysets can be merged using the bitwise or operator like this: n1 = <queryset ...> n2 = <queryset ...> merged = n1 | n2 What if I have an array of unspecified size array = [n1, n2, ...] and I'd like to do merged = n1 | n2 | ...? merged = array[0] for i in array: if (i in array): merged = merged | array[i] Is there a more elegant solution? Something like array.join(|)? -
Joining and grouping Django querysets
m1 = myModel.objects.filter(...) m2 = myModel.objects.filter(...) n1 = m1.values("date").annotate(car_crashes=Sum('car_crashes') * 1).values("date", "car_crashes") n2 = m2.values("date").annotate(car_crashes=Sum('car_crashes') * 2).values("date", "car_crashes") With this code, I get in n1 and n2 two querysets: <QuerySet [{'date': datetime.date(2008, 4, 1), 'car_crashes': Decimal(1.000)}, ... ]> <QuerySet [{'date': datetime.date(2011, 4, 1), 'car_crashes': Decimal(2.000)}, ... ]> Please note that they might not be of the same size and some dates might be in one queryset but not the other. How can I group these 2 querysets on the date field and sum car_crashes? -
Storing hierarchies/trees insdie a django model field?
First off, I know that there are packages like django-mptt and django-treebeard, but these don't look like what I am looking for. (There the goal seems to be to arrange all the model instances in a tree and the model has fields that encode the position of each instance. There is only one tree, nodes can be rearranged, deleted, or newly inserted.) The task: My goal, roughly speaking, is to have a model that stores trees. There are multiple trees to store in the database, and each instance of the model stores one of those trees. I'll try to illustrate two different usage examples of different complexity. The first is probably easy to implement, the second... I don't know. [Side question: Is there a name for what I am looking for? Searching for django+tree results in discussions of problems and solutions that are like django-mptt...] Simple case: Consider models for chapters and books. class Chapter(Model): heading = CharField() text = TextField() class Book(Model): name = CharField() structure = ???magic??? The chapter model stores the text parts of the book, so you'd have one instance holding heading and text on Topic A, another for Topic B, and so on. The book … -
Django: How to know the raw sql and the time taken by a model queryset
I am trying to know the 1) time taken or duration and 2) raw sql for any django model queryset Eg: users = User.objects.all() print(time_take for users) print(raw sql of users) -
Django not showing database updates
I have a django template that just lists out a postgresql table: <table> {% for prod in object_list %} <tr> <td><a href='{% url 'prod-detail' pk=prod.prod_id %}'>{{prod.prod}}</a></td> <td>{{prod.title}}</td> <td>{{prod.rank}}</td> <td>{{prod.date}}</td> <td>{{prod.error}}</td> </tr> {% endfor %} </table> The table was working fine until I decided to try testing what would happen if prod.title didn't exist. I went into PGAdmin and changed the title field to null on three of the products. When I reloaded the page, those fields still showed the data that I had removed. I am running postgresql 11.4, Python 3.73, and Django 2 on a Windows 10 Pro laptop. I tried stopping and restarting the Django server. The data persists. PGAdmin definitely shows the fields as null. I've searched for this issue, but I haven't come up with any answers. The Django documentation indicates that unless set otherwise connections don't persist... The code above is all I've tried. It continues to work fine, but it never reflects the updates that I've made to the database. I was expecting those fields to show as empty in my html table, but they still show the data that I removed. Thanks for any suggestions. --Al -
EB CLI - 403 when creating environment
I am brand new to ElasticBeanstalk, so any verbosity you can offer to help me understand what I'm doing wrong is greatly appreciated. I am getting the following 403 Forbidden Error within EB CLI when running eb create: ERROR: CommandError - An error occurred while handling git command. Error code: 128 Error: fatal: unable to access 'https://git-codecommit.us-east-2.amazonaws.com/v1/repos/origin/': The requested URL returned error: 403 My IAM User has the following permissions: AWSElasticBeanstalkFullAccess AWSCodeCommitFullAccess I've searched for any others that may be relevant, but couldn't find any obvious ones. My application is a Django app with the following file structure: streambeacon |_ .elasticbeanstalk |_ config.yaml |_ .venv |_ streambeacon-api *(django parent)* |_ application *(django app)* |_ payment *(django app)* |_ scripts *(django app)* |_ streambeacon *(django config)* |_ settings.py ** folder structure for reference, not complete. .elasticbeanstalk/config.yaml branch-defaults: master: environment: null group_suffix: null global: application_name: streambeacon-api branch: master default_ec2_keyname: xxxx-ommitted--xxxx default_platform: Python 3.4 default_region: us-east-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: origin sc: git workspace_type: Application I have read in another SO question that the issue for them was that port 443 wasn't exposed in their security group, but I am creating this environment via CLI & … -
shopping cart not save item using django session
I am not sure why django return an empty shopping cart when trying to use session. Using pdb i can see that the data are sent to the template but something is wrong somewhere. Before using session and while hardcoding without session i was able to make it work. I need assistance, please. view.py def cart(request): """ List of items in cart with session. """ try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) context = {"cart": cart} else: empty_message = "Your cart is empty, please keep shopping." context = {"empty": True, "empty_message": empty_message } return render(request, 'carts/cart.html', context) def update_cart(request, slug): """ Add items to cart with session. """ try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass if not product in cart.products.all(): cart.products.add(product) else: cart.products.remove(product) new_total = 0.00 for item in cart.products.all(): new_total += float(item.price) cart.total = new_total cart.save() return HttpResponseRedirect(reverse('carts:cart')) cart.html {% block content %} <div class="col-sm-8 col-sm-offset-2 mt-5 ml-5"> <div class="d-flex justify-content-between"> <h3 class="header mb-4">Cart</h3> <a href='{% url "products:list" %}'> <h5 class="card-title">List of Products</h5></a> </div> {% if empty %} <h4 style="text-align:center;">{{ empty_message }}</h4> {% … -
Django app on AWS EC2 not returning data for specific computers
My Django server does not return data from the AWS RDS database for some users. I have a Django server deployed to an AWS EC2 instance and setup using Nginx and Uwsgi. I am using an AWS RDS PostgreSQL database to store my data for the same. Every time the front end makes a request to the server, the server reads some data from the database and returns it as a JSON object. It works fine for me. However, some users have reported no data being revealed for them on the front-end. So, I tried logging the results of the API call, and I found that for the same request, the request from my computer gets some data, while from some other user's computer - the retrieved data object is empty. (Note: The user has 40Mbps internet speed, so it's not a speed issue per say) I thought it might be an issue with RDS, so I tried migrating to a different database, but that didn't fix it either. I also tried changing the instance region, but that didn't affect anything either. -
Custom User model error: AttributeError: 'CustomUser' object has no attribute 'is_anonymous'
Trying to set up a custom user model that extends the base user. Some user will have login information and some will not, but I still want all users logged. That's what I think the error is saying. In the default Django model they were logged, but now some users will just have just IP address and username. Other users will have more information like email, etc. Gettin this error: AttributeError: 'CustomUser' object has no attribute 'is_anonymous' Here is my custom user class: class MyUserManager(BaseUserManager): def create_user(first_name, last_name, address1, state, zipcode, email, username, password): user=self.model( first_name = first_name, last_name = last_name, address1 = address1, zipcode = zipcode, state = state, email=email, username = username, password = password ) user.is_superuser = False user.is_admin = False user.is_staff = False user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=25 ) last_name = models.CharField(max_length=25 ) address1 = models.CharField(null=True, max_length=100, blank=True) zipcode = models.CharField(max_length=10, null=True,blank=True) state = models.CharField(null=True, max_length=2, blank=True) email = models.EmailField(max_length = 250) username = models.CharField(max_length = … -
Adding fonts to django-summernote
I'd like to add some Google fonts to django-summernote as selectable fonts. I've loaded the font within the html file. I know that I'm doing this correct as the the rest of the text on the page uses this font (i.e. Questrial) I then go into my settings file and add Questrial to the 'fontname' line SETTINGS_DEFAULT = { 'iframe': True, 'airMode': False, 'empty': ('<p><br/></p>', '<p><br></p>'), 'width': 720, 'height': 480, 'toolbar': [ ['style', ['style']], ['font', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']], ['fontname', ['fontname', 'Questrial']], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['height', ['height']], ['table', ['table']], ['insert', ['link', 'picture', 'video', 'hr']], ['view', ['fullscreen', 'codeview']], ['help', ['help']], ], Even with this change, I don't have the ability to select the Questrial font in the summernote widget. Any help would be appreciated. Thanks! -
how to fix a static file heroku hosting problem and database
I am deploying my site in production in Heroku my I have static file issues and database Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" and init.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: I thought I put "procfile" in the wrong place actually no, it's the same level as manage. py -
How do I access POST Data in Django, "No connection adapters were found for '<QueryDict: {}>'"
Hi I was wondering why I can't access the data I submitted in a form in another view. Django keeps telling me "No connection adapters were found for ''" Here's my html: <div class="modal-body"> <form method="post"> {% csrf_token %} <div class="form-group"> <label for="recipient-name" class="col-form-label">Link</label> <input type="text" class="form-control" id="recipient-name"> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <a href={% url 'post-parse' %}> <button class="btn btn-info" type="submit">Submit</button> </a> </div> Here's my view.py: class PostParseView(PostCreateView): def get_initial(self): # Get the initial dictionary from the superclass method initial = super(PostParseView, self).get_initial() initial = initial.copy() recipe = AbstractParser(self.request.POST) ... ... My problem is the method self.request.POST doesn't work for me, I tested with different url's and my code works, but I can't access the url I submitted. If I replace self.request.POST with any url I want the code works, can anyone help me identify what I can do to make post work properly? Thank you!! -
Django + Nginx on subdomain Bad request 400
I need to deploy app to prod to subdomain. DNS A-record of app.mysite.com have value of machine. A-record of mysite.com have ip of different computer. Stack: Nginx, Django, Gunicorn. Nginx works fine on IP, but invokes 400 on subdomain. I've tried adding proxy_set_header values proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; but it doesn't help. nginx/sites-enabled/mysite: (If I change server_name ti IP it wirks fine) server { listen 80; server_name app.mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/mysite; } location / { proxy_set_header Host $host; include proxy_params; proxy_pass http://unix:/home/user/mysite.sock; } } settings.py ALLOWED_HOSTS = [ip of machine,'127.0.0.1', 'app.mysite.com','mysite.com'] I want app to work only at subdomain. How could I achieve it? Possibly helpful last Nginx process logs Aug 10 21:23:59 my-machine systemd[1]: Starting A high performance web server and a reverse proxy server... Aug 10 21:23:59 my-machine systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument Aug 10 21:23:59 my-machine systemd[1]: Started A high performance web server and a reverse proxy server. Aug 10 21:25:09 my-machine systemd[1]: Stopping A high performance web server and a reverse proxy server... Aug 10 21:25:09 my-machine systemd[1]: Stopped A high performance web server … -
How to execute python manage.py django management command via button on the website on Heroku
I have a Django management commands that I would like to run. I would like to have it available for a user by clicking the button and it would execute it. I do not need help to write one - I have them working, but always I need to run them from the terminal like: heroku run python manage.py syncdata Very convenient would be to just click the button on the running production website and it would start it for me. How can I make this happen on the site running on Heroku?