Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django shared model instance with per user overrides
I have a Django model that I want to centrally manage for my users. However, I also want users to be able to modify some fields for themselves, while allowing the central control to update the referenced model and have those updates appear for users (unless they have overriden this field). For this example, let's make it a store page, where users have their own whitelabeled pages. Items are created centrally, but each individual user can (optionally) edit the description and price for their own store. Centrally managed item: class StoreItem(models.Model): unit_id = models.CharField(max_length=200, unique=True) name = models.CharField(max_length=200) description = models.TextField() price = models.DecimalField(max_digits=5, decimal_places=2) Item that a user has overriden: class UserStoreItem(models.model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(StoreItem, on_delete=models.CASCADE) # I'd like these fields to be inherited from the item ForeignKey if not set description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) Is there a good way to do what I'm looking for? I've thought about just copying StoreItem for each user however that would lose the ability to be updated centrally. Bonus points if I'm able to have UserStoreItem inherit StoreItem's fields without having to define them twice. -
Ingredient - Stock - Order Database Design Django
I am designing an EPOS and I have some doubts regarding the stock - ingredient - order database schema that I came up with. Essentially, I am trying to find any flaws in the design so any feedback would be appreciated. Some of the requirements are: When an ingredient is received from a supplier, add it to the total count in stock Track quantity of each ingredient in stock When an order is placed, remove the quantity of the ingredient from stock Each product could have a different amount of an ingredient Calculate profit for each order based on spent ingredients for each product in the order My current DB design: Ingredient represents the concept of an Item that could be ordered from a supplier. It would be a single Model object in the DataBase. StockIngredient represents the total amount of the same Ingredient in the database, so each time there is an ingredient received from a supplier, or used for a product the total_weight would be changed, therefore, StockIngredient would also be a single object Model. IngredientForProduct would represent the quantity of the StockIngredient needed for each product. Product it's pretty self-explanatory, it has different IngredientForProduct -
django-select2 class-based or function based views
I'm thinking of using django-select2 project on my forms, but I'm mostly concerned about views do they have to be class-based views or I can use regular function views ? In the documentation they only mention class-based views but didn't say a word about function based views (like in snippet below) so I don't know if it will work with my regular function views? Thanks in advance. https://django-select2.readthedocs.io/en/latest/ A simple class based view will do, to render your form: # views.py from django.views import generic from . import forms, models class BookCreateView(generic.CreateView): model = models.Book form_class = forms.BookForm success_url = "/" -
Clerk matching query does not exist
I have a Clerk Model with the following field: status = models.CharField(max_length=50, null=True, choices=STATUS, default=STATUS[0][0]) And in login_view I want to check my user status. So I do: def login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) user_status = Clerk.objects.get(user__username=user.username) print(user_status) Here I get this error: Clerk matching query does not exist. -
Django Puput (Wagtail based blog) can't config disqus for comments
requirements: Python 3.8.6 Django 3.0.7 Puput 1.1.1 Wagtail 2.9 Over a Django project I installed Puput following instructions for a Standalone blog app and everything works fine until I want to activate the blog comments section with Disqus. The Puput comments documentation is very light so probably everything is straight forward but in my case something is missing or do not worked as intended. I did created a Disqus account to have the Disqus shortname and I registered my site on Disqus API Resurses for the Disqus api secret. Both of them requested on the admin site of the blog. On this point I have an Exception error/message: To use comments you need to specify PUPUT_COMMENTS_PROVIDER in settings. Request Method: GET Request URL: http://localhost/blog/why-you-should-include-webassembly-your-knowledge-portfolio-reasons-pragmatic-programmers/ Django Version: 3.0.7 Exception Type: Exception Exception Value: To use comments you need to specify PUPUT_COMMENTS_PROVIDER in settings. Exception Location: /home/helly/dev/.venvs/wanttolearn/lib/python3.8/site-packages/puput/templatetags/puput_tags.py in show_comments, line 102 Python Executable: /home/helly/dev/.venvs/wanttolearn/bin/python3 Python Version: 3.8.6 I tried to add a variable in my project settings.py PUPUT_COMMENTS_PROVIDER = 'Disqus' and this time I have a ValueError error not enough values to unpack (expected 2, got 1) Request Method: GET Request URL: http://localhost/blog/why-you-should-include-webassembly-your-knowledge-portfolio-reasons-pragmatic-programmers/ Django Version: 3.0.7 Exception Type: ValueError Exception Value: not … -
Django send_mail() only spits two arguments... I want three
I cannot seem to find an answer in Stackoverflow so I decided to post the issue. I am using django send_mail() and I include the NAME, EMAIL and MESSAGE but for some strange reason only NAME and EMAIL get sent. Basically, the third argument gets ignored and I cannot figure out why. CLARIFICATION: the email sends and works flawlessly, but I cannot get Django to spit the third argument for message. This is my code: def index(request): if request.method == "POST": message_name = request.POST['message-name'] message_email = request.POST['message-email'] message = request.POST['message'] send_mail( 'Email from ' + message_name, message, message_email, ['myemail@gmail.com'], ) return HttpResponseRedirect(reverse("index")) return render(request, 'base/index.html', {'message_name': message_name}) else: return render(request, 'base/index.html', {}) -
Browser back button scenario in Django Application
Please help me on the below scenario: i have created a django form,after filling the form there is chance the user may press the back button,at this point ,it should pop-up a message saying save or cancel the form.when i say "save" the form should submit and when i say cancel it should go to the previous page. after research,i understand javascript helps on this requirement,but i didnt find the related one to guide me. wat i need to add in my view and in my html code. how can i achieve ,iam a beginner in coding and also asking questions in stackoverflow. views.py def create(request): context = {} testlogFormset = modelformset_factory(testlogs, form=testlogForm) form = shoporderForm(request.POST or None) formset = testlogFormset(request.POST or None, queryset= testlogs.objects.none(), prefix='testlogs') # if request.method == "POST": if form.is_valid() and formset.is_valid(): with transaction.atomic(): shoporder_inst = form.save(commit=False) shoporder_inst.save() for mark in formset: data = mark.save(commit=False) data.shoporderno = shoporder_inst data.save() return redirect("/create") context['formset'] = formset context['form'] = form return render(request, 'prod_orders/create.html', context) -
Updating required ImageField from URLField (as option)
Given the setup below, is it possible to offer an optional, "virtual" URLField, that will set a required ImageField if the latter is not supplied? class ReleaseImage(models.Model): release = models.ForeignKey(Release, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/releases') class ReleaseImageForm(forms.ModelForm): image_from_url = forms.URLField(required=False) class Meta: fields = '__all__' model = ReleaseImage class ReleaseImageAdmin(admin.ModelAdmin): form = ReleaseImageForm I have attempted some different methods, without success, e.g. overriding clean on the ModelForm as below, but the form is not validated (complaining that image is required). def clean(self): super().clean() # ... download image from url ... image = SimpleUploadedFile(name="foo.jpg", content=bytes_downloaded_from_url) self.cleaned_data["image"] = image # self.instance.image = image # also attempted ... return self.cleaned_data What would be the best way of doing this? I'm getting somewhat confused whether this should live in save, clean, or clean_FOO, in the model, the modeladmin or the modelform -- or a combination of this somehow`? -
ajax call to filter select field in django
I have a form with two fields related to each other and I want the rooms filtered based on the class in the front form this is my code models.py class Class(models.Model): class_name = models.CharField(max_length=100) def __str__(self): return self.class_name class Room(models.Model): room_name = models.CharField(max_length=100) class = models.ForeignKey(Class,related_name='class',on_delete=models.SET_NULL, null=True) def __str__(self): return self.room_name views.py class CustomFormView(LoginMixin, TemplateView): template_name = 'form.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['class'] = Class.objects.values('pk','class_name') context['rooms'] = Room.objects.all() return self.render_to_response(context) def get_related_rooms(request): class_id = request.GET.get('class_id') rooms = Room.objects.filter(class_id=class_id) return render(request, 'form.html', {'rooms': rooms}) form.html <form id="custom_form" data-rooms-url="{% url 'app:get_related_rooms' %}"> Class Name: <select type="text" class="form-control"id="class_name" name="class_name"> {% for c in class %} <option value="{{ c.pk }}">{{ c.class_name }}</option> {% endfor %} </select> Room Name: </label> <select type="text" class="form-control" id="room_name" name="room_name"> {% for r in rooms %} <option value="{{ r.pk }}">{{ r.room_name }}</option> {% endfor %} </select> </form> //here is the ajax call to get the rooms <script> document.getElementById("#class_name").change(function () { var url = $("#custom_form").attr("data-rooms-url"); var classId = $(this).val(); $.ajax({ url: url , method: 'GET', data: { 'class_id': classId }, success: function (data) { $("#room_name").html(data); } }) }); </script> I want to make this: When I choose the class in the first select I want to … -
How to install mod_wsgi on aws linux 2
I am trying to install mod-wsgi on Linux 2. But I am getting this error error: command 'gcc' failed with exit status 1 ERROR: Command errored out with exit status 1: /home/ec2-user/venv/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-jzcb7l6h/mod-wsgi/setup.py'"'"'; __file__='"'"'/tmp/pip-install-jzcb7l6h/mod-wsgi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-zrs06wit/install-record.txt --single-version-externally-managed --compile --install-headers /home/ec2-user/venv/include/site/python3.7/mod-wsgi Check the logs for full command output. This is what I have tried yum install gcc openssl-devel bzip2-devel libffi-devel zlib-devel cd /usr/src sudo wget https://www.python.org/ftp/python/3.7.9/Python-3.7.9.tgz sudo tar zxvf Python-3.7.9.tgz ./configure --enable-shared ./configure --enable-optimizations #sudo make sudo make altinstall python3.7 --version cd ~ python3.7 -m venv venv source venv/bin/activate sudo yum update httpd sudo yum install httpd sudo yum install httpd-devel pip install mod-wsgi -
Django - Filter based on href?
Is there a way to filter based on the href contents? I have a .html page that has a link <td><a href="{% url 'ipDATA' %}">{{item.IP_Address}}</td> I have a function like this: def ipDATA(request, Host=IPs.IP_Address): items = NessusReports.objects.filter() context = { 'items': items, } return render(request, 'nessusdata.html', context) Right now, it returns the entire table, I want to filter based on the href. -
make staff user not edit superuser's username
In my django-admin panel i'm trying to make that the staff-user can make new user-accounts where it needs to add a username but the staff-user shouldn't be abel to edit the superuser's username. Right now this doesn't happens with the code. admin.py from typing import Set from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin # Unregister the provided model admin admin.site.unregister(User) # Register out own model admin @admin.register(User) class CustomUserAdmin(UserAdmin): def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) is_superuser = request.user.is_superuser is_staff = request.user.is_staff disabled_fields = set() # type: Set[str] if not is_superuser: disabled_fields |= { 'is_superuser', 'user_permissions', 'is_staff', 'date_joined', } # Prevent non-superusers from editing their own permissions if ( not is_superuser and obj is not None and obj == request.user ): disabled_fields |= { 'is_staff', 'is_superuser', 'groups', 'user_permissions', 'username', } for f in disabled_fields: if f in form.base_fields: form.base_fields[f].disabled = True return form # No delete button def has_delete_permission(self, request, obj=None): return False -
How do I fix these errors when installing a plugin for python bot?
I'm attempting to use Bots Open Source EDI Translator on my Mac, and successfully ran the webserver and monitor according to their guide*, but I receive this error whenever I try to read a plugin. Server Error (500) Traceback (most recent call last): File "/Users/myusername/Documents/Work/Python/bots_edi/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/myusername/Documents/Work/Python/bots_edi/venv/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/myusername/Documents/Work/Python/bots_edi/bots-3.2.0/bots/views.py", line 447, in plugin notification = -(u'Error reading plugin:"%s".')%unicode(msg) TypeError: bad operand type for unary -: 'unicode' *I did make some adjustments when following the installation guide. I created my virtual environment to operate with Python2.7, and when I tried to run the permissions line: sudo chown -R myusername /usr/lib/python2.7/site-packages/bots, it could not find the file. I'm assuming that's because I'm running a virtual environment, so I skipped it. Perhaps that's what's causing the issues now? If so, how do I manage my virtual environment with the sudo commands? Should I somehow be installing the dependencies (cherrypy, django, genshi) inside my virtual environment? -
Best way to serve npm packages with django?
I am using django as a backend with a few js packages installed with npm. I am currently accessing the packages by allowing django to serve /node_modules by adding it to the STATICFILES_DIRS. This has been working, but I have to go in the pacakge and find the js file I want to point to and then load it using a <script src="{% static .... This is a bit tedious and seems a bit "hacky." I also cannot figure out how to use imports/requires inside my js files. Is there a way to use imports or am I stuck loading everyting via script tags? I assume this is because django doesn't know how to server the npm packages appropriately? I've read a bit into webpack and I'm still unsure if webpack is a solution to my problem. Any advice? -
Running both Django and PHP on IIS (Internet Information Services) server
I have a previous application done with PHP and I have created another django project. I'm trying to run them both on IIS server as the existing PHP project is served through IIS. When I'm running PHP and Django separately, its working fine but if I configure IIS for running django and then go to the url of the php file (localhost/test.php), its testing for the route in urls.py and returning the possible urls like /home, /about. I need to display django views while visiting URLs in the urls.py and run php file while visiting the php url. Is there any way that I can do this? Any answer is appreciable. Thanks in Advance :) -
gunicorn.socket: Failed with result 'service-start-limit-hit '
I'm having this issue when I trying to deploy my app. Any ideas what could be?= -
Django create a models.ManyToMany and models.ForeignKey to the same table
All, I'm trying to configure my Django models.py file to include 2 tables with a ManyToMany and a ForeignKey link between the 2. The current configuration with only one entry works fine: Current models.py file: from django.db import models class CustTeamMembers(models.Model): member_first_name = models.CharField(max_length = 100) member_last_name = models.CharField(max_length = 100) member_email = models.EmailField(unique=True) member_phone = models.CharField(max_length = 25, blank=True) class Meta(object): ordering = ['member_last_name'] def __str__(self): return self.member_first_name + ' ' + self.member_last_name class CustTeamName(models.Model): cust_name = models.CharField(max_length = 100) cust_members = models.ManyToManyField(CustTeamMembers, blank=True) cust_meet = models.CharField(max_length = 40, blank=True) cust_status = models.TextField(blank=True) def __str__(self): return self.cust_name def get_members(self): return ", ".join([str(p) for p in self.cust_members.all()]) I would like to add another field above the "cust_members" entry. The reason for this is I have teams with multiple members and one of them is the lead for the team. I tried the following, but it failed: Alternate models.py file: from django.db import models class CustTeamMembers(models.Model): member_first_name = models.CharField(max_length = 100) member_last_name = models.CharField(max_length = 100) member_email = models.EmailField(unique=True) member_phone = models.CharField(max_length = 25, blank=True) class Meta(object): ordering = ['member_last_name'] def __str__(self): return self.member_first_name + ' ' + self.member_last_name class CustTeamName(models.Model): cust_name = models.CharField(max_length = 100) cust_lead = models.ForeignKey(CustTeamMembers, on_delete=models.CASCADE, blank=True) … -
Fetch data in many-many relationship in a single row
These are my models Team Table class Team(CommonModel): ****Other Fields**** name = models.CharField() game = models.ManyToManyField(Game, through='Team_Game') Mapper Table class Team_Game(CommonModel): game = models.ForeignKey(Game, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) status = models.SmallIntegerField(default=1) class Meta: db_table = 'team_game' Game Table class Game(CommonModel): name = models.CharField(max_length=128, blank=False, null=False, unique=True) status = models.SmallIntegerField(default=1) I want to retrieve team with id 1 and game associated with it Expected data: team.name, other_team_cols, [game_id1, game_id2] Query: team_data = Team.objects.filter(id=1).values('id', 'name', 'game__name') Output: [ { "id": "1", "name": 'abc', "game__name": "game1" }, { "_packageID": "1", "name": "def", "game__name": "game2" } ] Expected Output: { "id": "1", "name": 'abc', "game__name": ["gam1", "gam2"] } -
Is this possible that we use procedures to insert data but create two models and serializers ?DRF PYTHON
Is this possible that we use procedures to insert data but create two models and serializers . to validate the data because the procedure get fields from two tables? DJANGO REST FRAMEWORK PYTHON -
How to call a function by loading a string in Django?
I'm new to Django and I'm testing, In case I have my posts.html templete and I wanted to load all posts in a summarized form on the page, however one side would load the posts with even id and the other with odd id. I did a function in views.py and wanted to load all posts in posts.html. def posted(request): posts = Album.objects.all() for post in posts: if post % 2 == 0: return render(request, """<div class="container marketing "> <div class="row mb-2 " > <div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ post.title }}</strong> <h3 class="mb-0">{{ post.author.get_full_name }}</h3> <div class="mb-1 text-muted">{{ post.created_at|date:'d, M Y'}}</div> <p class="card-text mb-auto">{{ post.summary|safe }}</p> <a href="/post/{{ post.pk }}" class="stretched-link">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> <img class="bd-placeholder-img" width="200" height="250" src="{{post.image.url}}" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/></img> </div> </div> </div>""",) return render(request, """<div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-success">Design</strong> <h3 class="mb-0">Post title</h3> <div class="mb-1 text-muted">Nov 11</div> <p class="mb-auto">This is a wider card with supporting text below as a natural lead-in to additional … -
My Django Webblog project is not deploying on heroku
When I am trying to push my Django project on Heroku, each time it's showing this "failed to push some refs to .. " (check my provided screenshot). Even i have created a .gitignore file but even its not working. Here is the screenshot of problems -
Get django model correctly
I am trying to get the value of my model and get the values using a for loop but it gives me this I want it to print Gazou Gazou Gazou Gazou Gazou Gazou [<Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>] My views.py def watchlist(request): if request.method=='POST': name = User.objects.get(username=request.user.username) title = request.POST['title'] print(name) listing = Listing.objects.get(title=title) all_titles = Watchlist.objects.filter(name=name) print(all_titles) print(title) msg = "You already have this on your watchlist" a = [] for item in all_titles: a.append(item) print(a) if title in a: return HttpResponseRedirect(reverse("index")) else: watchlist = Watchlist.objects.create(taitle=title, name=name, title=listing) return HttpResponseRedirect(reverse("index")) else: user = request.user watchlist = Watchlist.objects.filter(name=user) return render(request, "auctions/watchlist.html", { "watchlist": watchlist }) My models.py class Watchlist(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE, null=True) taitle = models.CharField(max_length=100, null=True) title = models.ForeignKey(Listing, on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.taitle}" I am using django 1.11.29 and python 3.8.5 -
Is there a way to use a Django registered BaseSetting in a models save function?
I am overriding a model's save function to query Google's Geocoding API for the corresponding latitude/longitude coordinates to an address and save them to the model. I have registered a BaseSetting in Django admin with my API keys, and would like to access this registered setting inside my models.py to avoid hard-coding an API key. Handling it in the view is not an option given I would like to minimize the number of API calls. Here's some demo code: class DropoffLocationPage(models.Model): templates = "locations/dropoff_location_page.html" dropoff_address = models.CharField(max_length=40, blank=False, null=False) dropoff_city = models.CharField(max_length=40, blank=False, null=False) dropoff_state = models.CharField(max_length=2, blank=False, null=False) dropoff_zip = models.CharField(max_length=5, blank=False, null=False) dropoff_unit_number = models.CharField(max_length=10, blank=True) dropoff_latitude = models.CharField(max_length=25, blank=True) dropoff_longitude = models.CharField(max_length=25, blank=True) def get_coordinates(address): .... return response['results'][0]['geometry']['location'] def save(self, *args, **kwargs): address = str(self) location = get_coordinates(address) self.dropoff_latitude = location['lat'] self.dropoff_longitude = location['lng'] super(DropoffLocationPage, self).save() def __str__(self): return (self.dropoff_address + " " + self.dropoff_city + ", " + self.dropoff_state + " " + self.dropoff_zip + " " + self.dropoff_unit_number) @register_setting class GoogleAPISetting(BaseSetting): maps_api_key = models.CharField( max_length=255, help_text="Your Google Maps API Key" ) -
How to extend query table for reviews of people I follow with user details
I'm trying to create a Django project, and currently I have three models in use: the standard Django User, Review and Follow, given below: class Review(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) text_content = models.TextField(max_length=300) movie_rating = models.IntegerField() class Follow(models.Model): following = models.ForeignKey(User, on_delete=models.CASCADE, related_name="following") follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") What I want to get as a result is given user as a input, get all the reviews of people I follow. I used the following command Review.objects.filter(author__following__follower=user), and it gives me the user_id, text_content and movie_rating, but I'm not sure how to extend this table to add some things from the User model, such as first_name and last_name. -
How to set mode in AES using Django?
I created g-suite signup using Django it's yesterday working fine. but today I will check it throwing error(TypeError: new() missing 1 required positional argument: 'mode'). How to fix this issue. I tried many ways. but it's not working. a.py class rftoken token=models.chearfield() def pad(key): return key+ (BLOCK_SIZE - len(key) % BLOCK_SIZE) * PADDING def aes(self): p = AES.new(settings.COOKIE_SALT) return base64.b64encode(p.encrypt(rftoken.pad(str(self.id)))).decode() if rft: redirect.set_cookie('rtok', rtok.aes(), max_age=10 * 10 * 20 * 200) return redirect When I run the g-suite login code it's throwing this error Error TypeError: new() missing 1 required positional argument: 'mode'