Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap collapse doesn't collapse django
I am using django and i wanted to add a collapse function from bootstrap to my model, but it is not opening my content. I can't see whats wrong. When i click the button nothing happens. Could someone please explain me what's happening and why? Here is my code: base.html: <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Welcome to your workspace {% block title %}{% endblock %}</title> </head> <body> <div class="accordion" id="accordionQuestions"> {% block content %}{% endblock %} </div> <!----------------CLOSE CONTAINER-----------------> </body> </html> index.html: {% block content %} <h1 class="text-center mb-3">Welcome to your worspace!</h1> {% if latest_question_list %} {% for question in latest_question_list %} <div class="card mb-3"> <div class="card-header" id="heading{{ question.id }}"></div> <h2 class="mb-0"></h2> <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapse{{ question.id }}" aria-expanded="false" aria-controls="collapse{{ question.id }}">{{ question.question_text }} </button> </h2> </div> <div id="collapse{{ question.id }}" class="collapse" aria-labelledby="heading{{ question.id }}" data-parent="#accordionQuestion" > <div class="card-body"> <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'chiefworkspace:vote' question.id %}" class="text-center mb-3" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <div class="card mb-3"> <div class="card-body"> <input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ … -
how to export 3D avatar in fbx format on django-website
is there any piece of code to export my .fbx 3D avatar on the django-based website? i have gone through WebGl, three.js but can't solve the issue. thanks in advance. -
How to build a leaderboard in Django that allows for arbitrary querying and slicing?
I have a basic leaderboard in Django 2 that looks like this: from django.db import models class Leaderboard(models.Model): username = models.CharField(max_length=200) score = models.PositiveIntegerField() class Meta: indexes = [models.Index(fields=["-score"])] def __str__(self): return self.username I can produce a ranking of this leaderboard table using Django's built-in window functions Rank() and PercentRank(): from django.db.models import F, Window from django.db.models.functions import PercentRank, Rank entries = ( Leaderboard.objects.annotate( rank=Window( expression=Rank(), order_by=F("score").desc(), ), percentile=Window( expression=PercentRank(), order_by=F("score").desc(), ), ) ) print("Rank\tPercentile\tScore\tUser ID\tUser Name") for entry in entries: print(f"{entry.rank}\t{entry.percentile:.3f}\t{entry.score}\t{entry.id}\t{entry.username}") This produces a pageable table with the rankings: Rank Percentile Score User ID User Name 1 0.000 1000 564 Eager Guard 2 0.001 999 302 Top Hawk 2 0.001 999 747 Eager Whistler 2 0.001 999 842 Extreme Legend 5 0.004 997 123 Witty Guard 5 0.004 997 201 Arctic Elephant 7 0.006 996 21 Speedy Bear 7 0.006 996 678 Agile Player 9 0.008 995 562 Fast Hawk 10 0.009 994 467 Loyal Legend However, I am having difficulty querying for a specific User ID in the leaderboard and retrieving their rank and percentile. It seems that the result of the window functions are only being applied within the current queryset (ie, limited to the filter for … -
How to skip a column check with condition using Django ORM
In Django ORM how can we skip checking for a column if a condition is true? And how to check for that column with a specific value if the condition is false. For example, how can we achieve following mysql condition with Django ORM? IF(product.display_stock > 0,'0',product.hide) = 0 The need here is, if product's display_stock is > 0, then I don't care what the value of hide column contains. If display_stock = 0, then I need to confirm hide = 0. Any help form Django ORM experts is highly appreciated. Thanks. -
Webside name for Django
I just began to write some webapplications/websides on python django. I want to know -for later- is it possible to change the server name. I mean currently I have a server with a Ip port/adress and its Offline. My question is; 1) Is it possible to make the webside online on Internet for free or does it cost anythink? 2) Is it possible to get another servername/webadress than my current Ip for free or does it cost anythink? I hope I asked the questions correctly and Ill be happy if I can get a answer from Community.. Have a good day -
Django Wagtail - Images not showing up on BlogIndexPage
I am following along with the Wagtail's Your First Wagtail Site, specifically including the main image as a thumbnail alongside each post in the BlogIndexPage. Everything was working fine until I added custom HTML. Models.py: class BlogIndexPage(Page): templates = "blog/blog_index_page.html" max_count = 1 intro = RichTextField(blank=True) def get_context(self, request): # Update context to include only published guides, ordered by reverse-chron context = super().get_context(request) blogpages = self.get_children().live().order_by('-first_published_at') context['blogpages'] = blogpages return context content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] class BlogPage(Page): templates = "blog/blog_page.html" date = models.DateField("Post date") intro = models.CharField(max_length=250, blank=True, null=True) body = RichTextField(blank=True, null=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) categories = ParentalManyToManyField('blogs.BlogCategory', blank=True) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('date'), FieldPanel('tags'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ], heading="Blog information"), FieldPanel('intro'), FieldPanel('body'), InlinePanel('gallery_images', label="Gallery images"), ] blog_index_page.html: (Everything was working fine using Wagtail's example HTML, but once I added my own custom HTML the images stopped working. Inspect Element shows that the images .jpgs are being sourced correctly, they just don't show up. The URLS, title, and intro are working fine.) <div id="posts" class="post-grid grid-container clearfix" data-layout="fitRows"> {% for post in page.get_children … -
Pytest on Django Channels should not pass but it does
I am stuck, working with TDD my tests pass when they should not, no idea why. It should failed, Order model is not updated, so I think it should throw an error. Other thing is I could not log data when test passed. Django>=3.0.2,<3.1.0 djangorestframework>=3.11.0,<3.12.0 psycopg2>=2.8.4,<2.9.0 flake8>=3.7.9,<3.8.0 djangorestframework-simplejwt>=4.4.0,<4.5.0 channels>=2.4.0,<2.5.0 channels-redis>=2.4.2,<2.5.0 pytest-django>=3.8.0,<3.9.0 pytest-asyncio>=0.10.0,<1.0.0 test_websocket.py @database_sync_to_async async def test_user_can_create_orders(self, settings): settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS user = await create_user( email='employee@example.com', group='user' ) client = Client() client.force_login(user=user) communicator = WebsocketCommunicator( application=channel_routing, path='/notification/', headers=[( b'cookie', f'sessionid={client.cookies["sessionid"].value}'.encode('ascii') )] ) # send JSON msg to a server. await communicator.send_json_to({ 'type': 'create.order', 'data': { 'user' : user.id, } }) response = await communicator.receive_json_from() data = response.get('data') assert data['id'] is not None assert Order.REQUESTED == data['status'] assert data['employee'] is None assert user.email == data['user'].get('email') await communicator.disconnect() models.py class Order(models.Model): REQUESTED = 'REQUESTED' ACCEPTED = 'ACCEPTED' DECLINED = 'DECLINED' STARTED = 'STARTED' IN_PROGRESS = "IN_PROGRESS" READY = "READY" COMPLETED = "COMPLETED" STATUSES = ( (REQUESTED, REQUESTED), (ACCEPTED, ACCEPTED), (DECLINED, DECLINED), (STARTED, STARTED), (IN_PROGRESS, IN_PROGRESS), (READY, READY), (COMPLETED, COMPLETED), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField( max_length=20, choices=STATUSES, default=REQUESTED) def __str__(self): return f'{self.id}' def get_absolute_url(self): return reverse('order:order_detail', … -
If there a more concise way of accepting user queries in a django rest framework view
I've read through the django rest framework documenation and tried to get the filter backend working with no success. My work around was to overide the get_queryset in the view: def get_queryset(self): # create a var as a dict of the query parameters passed in by the user user_query = {key: value[0] for key, value in dict(self.request.query_params).items()} # this try block prevents the format argument used to return # json from being passed as a user query try: del user_query['format'] except KeyError: pass queryset = Foo.objects.filter(**user_query) return queryset My question is; is there a more concise way of doing it? or perhaps someone who can help me understand the django filter backend better. -
creating a confirm page in django when deleting
Following a tutorial where it uses a confirm page when you click the delete button. But what he's using is a class view (not sure if that's the right term. this is how he does it class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False Since I made my views different (came from a different tutorial), I want it to be consistent by using a post like usual but with a confirm page. NOTE: I do not want to use a confirm pop up like what they usually recommend on other posts. This is what I have @login_required def post_delete(request, id): post = Post.objects.get(id=id) if post.author != request.user: raise Http404("Can't find post") form = PostForm(request.POST or None, instance=post) print(form) if form.is_valid(): form.save() return HttpResponseRedirect('blog_posts_by_logged_user') context = { 'form' : form } return render(request, "blog/delete_confirm.html", context) Only issue here is, that I keep getting invalid, so I never get past the whole thing and it just reloads the confirm page. This is my delete/confirm.html template {% extends 'blog/base.html' %} {% block content %} <form method="POST" action=""> {% csrf_token %} <div>Are you sure you want to delete {{ … -
Selenium on Docker keeps giving 127 error (unexpectedly exited)
def setUp(self): chrome_options = Options() chrome_options.add_argument('--dns-prefetch-disable') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('disable-gpu') self.selenium = webdriver.Chrome('./chromedriver', chrome_options=chrome_options) super(FunctionalTesting, self).setUp() Above is my functional test code for a Django website I'm building. But then I keep getting this error message. File "/builds/XXX/XXX/XXX/tests.py", line 11, in setUp self.selenium = webdriver.Chrome('./chromedriver', chrome_options=chrome_options) File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__ self.service.start() File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 98, in start self.assert_process_still_running() File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 111, in assert_process_still_running % (self.path, return_code) selenium.common.exceptions.WebDriverException: Message: Service ./chromedriver unexpectedly exited. Status code was: 127 Any idea to solve the problem? Note that the problem is not at the "./chromedriver" directory, I have set up the CI/CD script so it will have chromedriver at that spot -
How to show/hide items of the list in Django? (using JS or JQuery)
I'm writing website using Django framework, but i am newbie in this web-framework, and i don't know how to work with JavaScript in Django templates. I just wanted to show/hide items of the list onclick, but i show/hide only first or last item. My code: {% for mysong in album.song_set.all %} <li onclick=action()><a>CLICK ME</a></li> <div id="{{mysong.id}}"> <h1>{{mysong}}</h1> <img src="{{album.album_logo}}" width="300px"><br/> <h2>Song: {{mysong.song_title}}</h2> <h2>Artist: {{album.artist}}</h2> <h2> <audio controls> <source src="{{mysong.audiotrack.url}}" type="audio/mpeg"> </audio> </h2> </div> <script> function action() { var added_item_button = document.getElementById('{{mysong.id}}'); var actualDisplay = getComputedStyle(added_item_button).display; if (actualDisplay == 'none') { added_item_button.style.display = 'block'; } else { added_item_button.style.display = 'none'; } } </script> {% endfor %} That's how i tried to show/hide items of the list that i iterated over. But it seems, that's doesn't work like that. Thanks, any help will be appreciated. -
How can i show all fields in admin panel - Django
models.py class Company(models.Model): name = models.CharField(max_length=20) location = models.CharField(max_length=20) date_created = models.DateTimeField() Admin.py class CompanyAdmin(admin.ModelAdmin): list_display = [name,location,date_created] Register your models here. admin.site.register(Company,CompanyAdmin) Instead of writing write each one field(list_display = [name,location,date_created] ) there is an way to get all fields in admin??? -
Is it possible to subscribe ROS topic with a Django web-app?
I want to know if it's possible to bind ROS and Django in order to have a web-page which shows the state of a ROS controlled robot. I just want to have a Django application which subscribe a ROS topic and get the state about the robot, then this application should be able to show these data on a status page. For now I think that the easiest way is to have a ROS node which write data in files, and the Django app should open and read this data in order to show infos on a page ... But I think it's not very efficient and not bug-proof. Can you help me ? -
What is the best way for nest User serializers in Django Rest Framework?
I try to return a "Store Data" in a ModelSerializer from DRF with two keys named owner and collaborators that contain an User Serialized data. When I send a GET request I recieved only the User ID. I have this: Serializer class StoresSerializer(serializers.ModelSerializer): class Meta: model = Stores fields = "__all__" View class StoresAPI(viewsets.ModelViewSet): serializer_class = StoresSerializer queryset = Stores.objects.all() Response { "id": 13, "store_name": "Store Title", "store_website": "https://url.com.", "store_image": "https://url.com", "created_at": "2020-04-05", "owner": 2, "collaborators": [ 2, 3 ] } Deseable Response { "id": 13, "store_name": "Store Title", "store_website": "https://url.com.", "store_image": "https://url.com", "created_at": "2020-04-05", "owner": { "username": "ownerUser", "email": "user@mail.com", "id": 4, "first_name": "owner", "last_name": "LastName" }, "collaborators": [{ "username": "usr", "email": "user@mail.com", "id": 2, "first_name": "First", "last_name": "LastName" }, { "username": "usr", "email": "user@mail.com", "id": 3, "first_name": "First", "last_name": "LastName" }] } I try adding an UserSerializer in StroreSerialer but I get fields errors when I try to post data. class StoresSerializer(serializers.ModelSerializer): owner = UserSerializer() collaborators = UserSerializer(many=True) class Meta: model = Stores fields = "__all__" Thanks for read this, I hope you help me! -
how to create product auto Code generator python django
I have a product class in the Django model. Over there are product name, category and department name (foreign key). so I want to create an automatic code generator that will generate automatically like 2 or 3 alphabets as category name and 3 alphabet department name and 6 digits number. for example: COM-ELC-000001 '''class Item(models.Model): item_name = models.CharField(max_length=255, blank =True) description = models.CharField(max_length=255, blank=True, null=True) item_choice = ( ('IT','IT'), ('Electronics', 'Electronics') ) item_type = models.CharField(max_length=255, blank =True, choices = item_choice ) code = models.CharField(unique=True, max_length=255) unit = models.CharField(max_length=255, blank=True, null=True) company = models.ForeignKey(Company, on_delete = models.SET_NULL, null =True,blank=True) department = models.ForeignKey(Department, on_delete = models.SET_NULL,null= True, blank=True) ''' -
is there a way to use due PWA with Django templates?
I am trying to build a PWA application with @vue/pwa and Django. I set up vue with Django with Webpack loader and now when I want to build it it runs the service-worker on static url any ideas? -
Disable gunicorn glogger and use Django LOGGING config
I am having trouble to properly config gunicorn and Django logging to work together. I have managed to make gunicorn pass the errors like 404 /favicon.ico to my Django log however I am not able to catch other levels no matter what I pass as --log-level for gunicorn. Here is the loggers section in my settings.py 'loggers': { 'django': { 'handlers': ['console', 'django_info_file', 'django_error_file'], 'propagate': True, }, 'gunicorn.access': { 'level': 'INFO', 'handlers': ['gunicorn_access'], 'propagate': True, 'qualname': 'gunicorn.access' }, 'gunicorn.error': { 'level': 'INFO', 'handlers': ['gunicorn_error'], 'propagate': True, 'qualname': 'gunicorn.error' } } ... and appropriate handlers 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'django_info_file': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'project_name/logs/django/info.log'), 'formatter': 'verbose' }, 'django_error_file': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'project_name/logs/django/error.log'), 'formatter': 'verbose' }, 'gunicorn_access': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'project_name/logs/gunicorn/access.log'), 'formatter': 'verbose' }, 'gunicorn_error': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'project_name/logs/gunicorn/error.log'), 'formatter': 'verbose' } }, So what I have tried so far: --log-level=debug --log-file=- --capture-output --enable-stdio-inheritance --access-logfile=- --error-logfile=- On the Django side I have tried with: 'disable_existing_loggers': True, (both True and False) setting DEBUG=True and False to make sure require_debug_false is … -
Architecture of application using Angular + Django + Flask and How to integrate them?
I am building an application with Angular + Django + Flask, below are the details of the architecture that are finalized for the implementation: We want to read data from MySQL database using flask microservice and show it to the user using angular UI. Django will be used for managing admin functionality. We decided to use flask despite the Django rest framework because of microservices architecture. Jenkins will be used for CI/CD and docker for deployment. What approach should be used if I want my angular UI to be served by Django application as I don't want to run a separate server for it and data in UI to be fed by flask microservice. I am facing a problem with how to integrate them. I have searched a lot but didn't found any good solid solutions. Please guide me on how should I integrate them. -
Django deploy with gunicorn failed
Im trying to dpublish my django App. After uploading this project and setup virtualenvirement testing with runserver and gunicorn --bind 0.0.0.0:8000 mysite.wsgi I can open my testpage on Webbrowser. But, after creating gunicorn_Test_Page.socket and gunicorn_Test_Page.service files, I cant open my testpage. After testing with curl –unix-socket /run/gunicorn_Test_Page.socket localhost I get this error curl: (3) Failed to convert –unix-socket to ACE; string contains a disallowed character curl: (3) <url> malformed access denied. But what kind of disallowed charakter? I cant find any logfiles for gunicorn service [Unit] Description=gunicorn daemon Requires=gunicorn_Test_Page.socket After=network.target [Service] User=localuser Group=www-data WorkingDirectory=/home/websites/Test_Page ExecStart=/home/websites/Test_Page/Test_Page_venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn_Test_Page.sock config.wsgi:application [Install] WantedBy=multi-user.target socket [Unit] Description=gunicorn daemon [Socket] ListenStream=/run/gunicorn_Test_Page.sock [Install] WantedBy=sockets.target what disallowed character is that? how can i find out? -
How to get Django/Wagtail to resolve this url
I feel like a heel asking this because I'm sure the answer is simple. Nevertheless I've spent hours researching and testing possible solutions and I have been left hairless. In the project harmony I have written my own login page and it resides in an app called users. I have another app called your_harmony. To proceed beyond the your_harmony page, users need to login. your_harmony.html {% if user.is_authenticated %} <h1>{{ self.sub_title|richtext }}</h1> You are logged in as: {{ user.username }} &nbsp <a href="/users/logout">Click here to logout</a> ... {% else %} You must login to access this page. <a href="/users/login">Click here to login</a> {% endif %} harmony.urls urlpatterns = [ ... url(r'your-harmony/', include('your_harmony.urls')), url(r'^users/', include('users.urls')), ... your_harmony.urls urlpatterns = [ path('', views.your_harmony, name='your_harmony') ] The url /users/login uses users/views.py to display the login form views.py RETURN_FROM_LOGIN_URL = 'your-harmony' RETURN_FROM_LOGIN_URL = 'your_harmony/your_harmony.html' def login_view(request): form_context = {'login_form': LoginForm,} url = "users/login.html" if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) url = RETURN_FROM_LOGIN_URL else: messages.error(request, 'Your account is not enabled!') context = {} else: messages.error(request, 'Your username or password was not recognized!') context = form_context else: context = … -
How can I make Django mysqlclient package being detected with mod_wsgi and virtualenv?
I have a Fedora 32 workstation with apache2 and Python 3.8 as default. I want to use it as server for my Django 3 app. I've already installed latest version of mod_wsgi (compatible with python3.8) and it's already enabled in apache modules. But I keep getting an error in apache error_log: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? The answer is YES, I've installed mysqlclient with pip install mysqlclient (in my virtualenv). And actually it exists: /var/www/virtualenv/lib/python3.8/site-packages/mysqlclient-1.4.6-py3.8.egg-info I think I have an issue in my .conf file for mod_wsgi. It usually worked in another developments that I've made, but I'm not getting the point of why it's not working now. This is my .conf MOD_WSGI settings: WSGIDaemonProcess myapp python-path=/var/www/myproj:/var/www/virtualenv/lib/python3.8/site-packages WSGIProcessGroup myapp WSGIScriptAlias /myapp /var/www/myproj/myproj/wsgi.py I have made the same configurations in another developments in the past, and it worked fine. I thought it would work. It's not a module version issue because when I run it with manage.py runserver it works fine. Using gunicorn is not an option at the moment. I need to get this working with mod_wsgi. Thanks in advance! -
Compatiblilty between Django rest Framework and Bootstrap
Django 3 Bootstrap 4 I have an Django app I've created (not live) and I've used bootstrap to make it nice and pretty (and mobile responsive). My goal is to end up with a react front end, but I'm not very good with react yet. Is it possible to switch to Django Rest Framework and keep bootstrap 4 or is drf and Bootstrap competing technologies? If I can, it'll let me be ready for react when I feel comfortable implementing it -
How can the super user make some user inactive?
I am trying as a super user to make some user inactive. In the front end I have a drop-down list with all users and a side I have a submit button. In the back-end I wrote this code. The code doesn't work. What is wrong? if request.method=='POST': user = request.user user.is_active = False user.save() messages.success(request, 'Profile successfully disabled.') return redirect('index') -
Django creating ManyToMany relationships
I am building an app where users can add what courses they are taking with their details. My intention is to view all the users enrolled in a course based on course code regardless of the other details of the course (Such as time of enrollment). Currently, my model for course is: class Course(models.Model): class Semester(models.TextChoices): SPRING = '1', 'Spring' SUMMER = '2', 'Summer' FALL = '3', 'Fall' WINTER = '4', 'Winter' NONE = '0', 'None' class Difficulty(models.TextChoices): EASY = '1', 'Easy' MEDIUM = '2', 'Medium' HARD = '3', 'Hard' FAILED = '4', 'Failed' users = models.ManyToManyField(Profile,related_name='courses') course_code = models.CharField(max_length=20) course_university = models.CharField(max_length=100) course_instructor = models.CharField(max_length=100) course_year = models.IntegerField(('year'), validators=[MinValueValidator(1984), max_value_current_year]) course_likes = models.ManyToManyField(Profile, blank=True, related_name='course_likes') course_dislikes = models.ManyToManyField(Profile, blank=True, related_name='course_dislikes') course_semester = models.CharField( max_length=2, choices=Semester.choices, default=Semester.NONE ) course_difficulty = models.CharField( max_length=2, choices=Difficulty.choices, default=Difficulty.MEDIUM ) def __str__(self): return self.course_code def save(self, *args, **kwargs): self.course_code = self.course_code.upper().replace(' ', '') self.course_university = self.course_university.strip().lower() self.course_instructor = self.course_instructor.strip().lower() super(Course, self).save(*args, **kwargs) How can I view all the users with the same course number? Is this database structure appropriate for this use? I am trying to build a method called 'get_users_enrolled' but I am stuck on how should the query be to get the list … -
Storing Multiple Payment Methods + Shipping Addresses
Is there any Django plugin out there that will facilitate the ability for users to add multiple payment methods + shipping addresses to their user profile? Preferably something around the lines of a drop down of all the payment/addresses they have but also the ability to add additional ones. Thanks!