Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i access the context data in the template?
context_object_name = 'item_list' template_name = 'krop_view.html' model = Item def get_queryset(self): user = self.request.user #gets current user object krop = get_object_or_404(Krop, owner=user) return Item.objects.filter(krop=krop) def get_context_data(self, **kwargs): context = super(KropListView, self).get_context_data(**kwargs) user = self.request.user context['krop'] = Krop.objects.filter(owner=user) return context A "Krop" is technically a shop with items, i can get all items for the shop owned by the current user. I want to also access data from the Krop model so I passed in the krop context data related to current user. How do I access this context data in the template? I've tried and looked up ways to get the specific variables like: {{ krop.owner }} {{ item_list.krop.owner }} ultimetley I want to access data from two different tables, but for one page. Please and thank you!!! -
How can I display pandas dataframe into django template?
I have a pandas dataframe and i want to show this dataframe into my django template. But everytime the code compile successfully without showing any table in my django web app. What am i missing here? My data frame looks like this: dataframe sample and my html looks like: <div class="row" style="margin-bottom: 20px;"> <div class="col-md-3"> </div> <div class="col-md-9"> <div class="card" style="width: auto;"> <div class="card-body"> <h3 class="h3">Total match data and Profit Mergin</h3> <br> <table class="table table-striped"> <tr> <th>Total Contest</th> <th>Total Entry Amount</th> <th>Total Seat</th> <th>Total Winning Amount</th> <th>Total Team Capacity</th> <th>Profit Mergin</th> {% for value in final_data.iterrows %} <tr> <td>{{ value.0 }}</td> <td>{{ value.1 }}</td> <td>{{ value.2 }}</td> <td>{{ value.3 }}</td> <td>{{ value.4 }}</td> <td>{{ value.5 }}</td> </tr> {% endfor %} </table> </div> </div> </div> </div> i tried final_data.itertuplus but still got the same result. What should i do now? -
AttributeError: 'list' object has no attribute 'first'
lebel_months = [] members_exps = [] for member in team.members.all(): qs = Profile.objects.expenses_per_month(member.user) clr = color_picker() member_qs = [] for exp in qs: user = get_object_or_404(User, id=exp.user_id) month = exp.month summary = exp.sum if month not in lebel_months and month is not None: lebel_months.append(month) if month is not None and summary is not None: member_qs.append({ 'user': user.username, 'clr': clr, 'month': month, 'summary': summary}) if member_qs: members_exps.append(member_qs) print(members_exps[0]) print(members_exps.first()) outputs: with [0] everything works [{'user': 'serj', 'clr': '#71CABC', 'month': datetime.datetime(2020, 3, 1, 0, 0, tzinfo=<UTC>), 'summary': 128400}, {'user': 'serj', 'clr': '#71CABC', 'month': datetime.datetime(2020, 4, 1, 0, 0, tzinfo=<UTC>), 'summary': 53500}] with first() AttributeError: 'list' object has no attribute 'first' First print statement works. Second print statement catch an error. What am I doing wrong? -
Self-referencing foreign keys are listing everything if the value is null in Django-admin Page
I have a django model as below: class Words(models.Model): bare = models.CharField(max_length=100) accented = models.CharField(max_length=100) derived_from_word = models.ForeignKey('self', models.DO_NOTHING, blank=True, null=True, related_name='derived_words', related_query_name='derived_word') There is a field derived_from_word which shows that some of the words are derived from some other word. If it is not derived from any word so the field value is NULL. What issue i am having that when i register this model in the django-admin and when i opened any of the word for editing, the derived_from_word field is listing all the words and i can not find a way for it to list only the derived word or the NULL value. Due to high load of the words the drop down list is making the page unresponsive. -
Deploying Django To Heroku gives server error (500)
please i know this question has been asked several times but with those answers i still haven't solved it.I turned debug to False in my settings.py file (but before I turned it to false, everything was working perfectly) and when I ran git push heroku master and went to my website,I got an error saying Server Error (500). please i need help. please here is my settings.py import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'KEY' DEBUG = False ALLOWED_HOSTS = ['.herokuapp.com'] INSTALLED_APPS = [ 'app.apps.AppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' django_heroku.settings(locals()) here is my wsgi.py import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application)] here is my procfile web: gunicorn mysite.wsgi here is also the log 2020-04-03T23:19:17.048794+00:00 heroku[router]: at=info method=GET path="/" host=jimtec.herokuapp.com request_id=f256ae96-58b7-4b3d-8918-ebe9c5039a8f fwd="102.176.94.105" dyno=web.1 … -
How will I connect my index.html to my views.py?
I tried doing this: But my page says that TemplateDoesNotExist. What should I do? -
Type error: Profile object is not iterable
First time using a custom user model so I'm having trouble referencing the user object in views. I have tried a number of things but I'm really having difficulty grasping how to reference the user object within views with what I am trying to do. error TypeError at /mingle/ 'Profile' object is not iterable Request Method: GET Request URL: http://localhost:8000/mingle/ Django Version: 2.2.3 Exception Type: TypeError Exception Value: 'Profile' object is not iterable Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py in inner, line 257 Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 Python Version: 3.7.3 Python Path: ['/Users/papichulo/Documents/DatingApp', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/papichulo/Library/Python/3.7/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'] Server time: Sat, 4 Apr 2020 01:30:02 +0000 error is showing up here **description = Profile.objects.get(request.user).description ** **views.py, part that's giving me an error ** from __future__ import unicode_literals from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth import logout from django.contrib.auth import login, logout, authenticate from dating_app.forms import RegistrationForm,ProfileUpdateForm from .models import Profile from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User import os from django.core import serializers import json from django.contrib.auth import get_user_model User = get_user_model() def mingle(request): try: user = (Profile.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0]) except IndexError: user = None print(User.username) try: description = models.Profile.objects.get(user=request.user).description except … -
heroku 404 with django on deploy from git
I am having the error 404 when i open or deploy my app on heroku on the logs it doesnt show an actual line of error, i have follow the guidelines on the heroku and still i dont get it , already done the debug and disable with the collectstatic , did the migrate and makemigrations , check wsgi according to the whitenoise recent version which is moving it from that file my settings.py import os import django_heroku import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '******' DEBUG = False TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'buscador', 'bootstrap4', 'gunicorn', ] 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 = '*****.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '******.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': True, 'LOGGING': { 'version': 1, 'loggers': { 'djongo': { 'level': 'DEBUG', 'propogate': False, } }, }, 'NAME': '****', 'CLIENT': { 'host': 'mongodb+srv://*****:*****@mongodb-cluster-us-east-1-yuln1.mongodb.net/test?retryWrites=true&w=majority', } } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, … -
Django 'extends' in html file from another app cover 'original' html file
I'm using base.html from another app, and in another app, it works perfectly. But in new app, I extends it, and I could load base.html with stylesheet, but the problem is they only load base.html file. I have no idea why it happens, and just guess maybe it's because of TemplateView and ListView, cuz I haven't used it before, so I can just guess that's the only reason. But I want to use it as well. This is my code. New app is 'search', another app is 'posting'. search/templates/search/index.html {% extends "posting/base.html" %} {% block contents %} <div class='searchform'> <form action="{% url 'search:results' %}" name="se" method="GET"> <label for='search'>What are you looking for?</label> <input type="text" name='q'> <input type="submit"> </form> </div> <script src="" async defer></script> {% endblock %} search/templates/search/beerlist.html {% extends "posting/base.html" %} {% block contents %} <ul> {% for beer in beerlist %} <li><a href="/search/{{ beer.id }}">{{ beer.name }}</a></li> {% endfor %} </ul> {% endblock %} serach/views.py ... class index(TemplateView): template_name = 'search/index.html' class Results(ListView): model = Beerinfo template_name = 'search/results.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Beerinfo.objects.filter( Q(name__icontains = query) | Q(label__icontains = query) ) return object_list ... search/urls.py urlpatterns = [ path('', TemplateView.as_view(template_name = "search/index.html"), name='index'), path('results', views.Results.as_view(template_name … -
Django Rest Framework, overwrite _declared_fields attribute of serializer meta class
I am trying to decorate a serializer in order to add help text, like so: def help_decorator(*args, **kwargs): def inner(cls, sources=kwargs["sources"]): for k,v in sources.items(): cls._declared_fields[k].help_text = v return cls return inner help_text_source = {"foo": "help_foo", "bar": "help_bar"} @help_decorator(sources=help_text_source) class FoobarSerializer(serializers.Serializer): foo = serializers.CharField(max_length=10) bar = serializers.IntegerField() I've put a debugger into the function, and cls._declared_fields has been modified as expected. Then, the Serializer Meta class is instantiated to return a Serializer class: serializer = FoobarSerializer() Inspecting serializer.fields["name_of_fields"], shows that none of the fields have retained the help text. -
HTML Video tag not finding file
Using Django, trying to pull a video from a model. I appear to be pulling the correct file path but the video isn't being located. Have tried adding the full system directory from hard drive rather than just the context folder, hasn't worked out for me either. Have confirmed that video is in that location. Should I be using statics for this? Or not because it's located in a model? video_output.html {% extends 'highlights/base.html' %} {% block content %} {% for video in highlights %} <video width="320" height="240" controls> <source src="/media/{{ video.highlight }}" type="video/mp4"> Your browser does not support the video tag </video> {% endfor %} {% endblock %} From views.py def video_output(request): entrydata = Video.objects.last() context = { 'highlights' : Highlight.objects.filter(sourcevideo=entrydata.video_id) } return render(request, 'highlights/video_output.html', context) Console output [04/Apr/2020 11:32:13] "GET /highlights/outputs HTTP/1.1" 200 1960 Not Found: /media/highlights/812.mp4 Not Found: /media/highlights/811.mp4 [04/Apr/2020 11:32:14] "GET /media/highlights/812.mp4 HTTP/1.1" 404 2129 [04/Apr/2020 11:32:14] "GET /media/highlights/811.mp4 HTTP/1.1" 404 2129 Not Found: /media/highlights/814.mp4 Not Found: /media/highlights/813.mp4 [04/Apr/2020 11:32:14] "GET /media/highlights/814.mp4 HTTP/1.1" 404 2129 [04/Apr/2020 11:32:14] "GET /media/highlights/813.mp4 HTTP/1.1" 404 2129 Not Found: /media/highlights/815.mp4 Not Found: /media/highlights/816.mp4 [04/Apr/2020 11:32:14] "GET /media/highlights/815.mp4 HTTP/1.1" 404 2129 [04/Apr/2020 11:32:14] "GET /media/highlights/816.mp4 HTTP/1.1" 404 2129 Not Found: /media/highlights/817.mp4 [04/Apr/2020 … -
Heroku Django ModuleNotFoundError: No module named 'my_app'
My app (called 'my_app") in Django seems to be present on the Heroku Postgres database, and my_app is running when I python manage.py runserver from the command line. However when I run my_app in Heroku I get the error ModuleNotFoundError: No module named 'my_app' I also get the error [ERROR] Exception in worker process I have had a look at the requirements file and procfile but could see nothing wrong. I also went through the tutorial I used to develop this app and cannot for the life of me find anything amiss. Here is the full code error log for what it's worth: 2020-04-03T18:40:25.066140+00:00 app[web.1]: [2020-04-03 18:40:25 +0000] [4] [INFO] Listening at: http://0.0.0.0:59726 (4) 2020-04-03T18:40:25.066304+00:00 app[web.1]: [2020-04-03 18:40:25 +0000] [4] [INFO] Using worker: sync 2020-04-03T18:40:25.072150+00:00 app[web.1]: [2020-04-03 18:40:25 +0000] [10] [INFO] Booting worker with pid: 10 2020-04-03T18:40:25.086009+00:00 app[web.1]: [2020-04-03 18:40:25 +0000] [10] [ERROR] Exception in worker process 2020-04-03T18:40:25.086011+00:00 app[web.1]: Traceback (most recent call last): 2020-04-03T18:40:25.086011+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-04-03T18:40:25.086012+00:00 app[web.1]: worker.init_process() 2020-04-03T18:40:25.086012+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-04-03T18:40:25.086013+00:00 app[web.1]: self.load_wsgi() 2020-04-03T18:40:25.086013+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-04-03T18:40:25.086014+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-04-03T18:40:25.086014+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-04-03T18:40:25.086015+00:00 app[web.1]: self.callable … -
unindent does not match any outer indentation level error appearing
I am trying to combine these two views. This is what I have. MenuView is to combine with add_to_menu so that if the if statement returns negative, the menuview portion still runs and displays the menu on my html page. If the if statement is positive, it still shows the menu, but also adds the entered information into the database. I can only get one or the other to work at a time. Views.py: class MenuView(ListView): model = Product template_name = 'mis446/edit-menu.html' context_object_name = 'show_menu' def add_to_menu(request): if request.method == 'POST': if request.POST.get('name') and request.POST.get('price') and request.POST.get('nickname'): post=Product() post.name= request.POST.get('name') post.price= request.POST.get('price') post.slug= request.POST.get('nickname') post.save() model = Product context_object_name = {'show_menu'} return render(request, 'mis446/edit-menu.html', context_object_name) else: model = Product context_object_name = {'show_menu'} return render(request,'mis446/edit-menu.html') -
Django model form, adding a user id when creating new note
I'm pretty new to Django, I've been stuck on this view for a little while. My goal with this form is to be able to create a small note on a "Property" about maintenance or other information. The note would log the time, date, note and the user that recorded the note. Any help would be appreciated. View: @login_required(login_url="login") def createNote(request, pk): PropertyNoteFormSet = inlineformset_factory( Property, PropertyNote, fields=('note', 'user',)) property_note = Property.objects.get(id=pk) form = PropertyNoteFormSet(instance=property_note) # form = OrderForm(initial={'customer': customer}) if request.method == "POST": print(request.POST) form = PropertyNoteFormSet( request.POST, instance=property_note) if form.is_valid(): form.save() return redirect("/") context = {"form": form} return render(request, "dashboard/create_note.html", context) Here is the ModelForm: class PropertyNoteForm(ModelForm): class Meta: model = PropertyNote fields = ['note'] exclude = ['user'] Here is the Model: class PropertyNote(models.Model): airbnb_name = models.ForeignKey(Property, blank=True, null=True,on_delete=models.CASCADE) note = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.note The form comes out with around 4 boxes to fill in. Currently it works, but you have to actually select the user that is posting the note, I would like this part to be handled automatically and use the current logged in user. I think I still have a whole lot of holes in … -
token authentication works fine in localhost but not working on ubuntu server (Djangorestframework)
i write a server in django and i have made an api's in django rest framework. All api's works fine in local host but when i upload my project to the ubuntu server then its token authentication is not working. It always gives {"detail":"Authentication credentials were not provided."} My all code runs perfect on locallost but on ubuntu server it gives me an error. views.py class ManageUserView(generics.RetrieveUpdateAPIView): serializer_class = serializers.UserSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_object(self): return self.request.user Serializers.py* class UserSerializer(serializers.ModelSerializer): """ Serializer for the users object """ class Meta: model = get_user_model() fields = ('id', 'email', 'password', 'user_type') extra_kwargs = {'password': {'write_only': True, 'min_length': 8}} def create(self, validated_data): """ Create a new user with encrypted password and return it""" print(validated_data) return get_user_model().objects.create_type_user(**validated_data) def update(self, instance, validated_data): """ Update a user, setting the password correctly and return it """ password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user -
How to save custom fields with user data on Django?
I've created a "Account" class so i can get more columns on user information: class Account(AbstractUser): company_name = models.CharField(max_length=50) company_department = models.CharField(max_length=50) company_employees_quantity = models.IntegerField(default=1) def __str__(self): return self.username I've also created a form with this data so i can receive the information on my view. class AccountCreationForm(UserCreationForm): company_name = forms.CharField(max_length=50) company_department = forms.CharField(max_length=50) company_employees_quantity = forms.IntegerField() class Meta: model = Account fields = ('username', 'email') The problem is when the client send the data though the form, i receive all the fields but only the "core" user information is inserted on the database. class SignUpView(CreateView): form_class = AccountCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' If o add a method form_valid on on view o can save the data field by field like this: class SignUpView(CreateView): form_class = AccountCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' def form_valid(self, form): if form.is_valid(): account = form.save() account.company_name = form.cleaned_data["company_name"] account.company_department = form.cleaned_data["company_department"] account.company_employees_quantity = form.cleaned_data["company_employees_quantity"] account.save() return redirect(self.success_url) return super().form_invalid(form) But this look weird to me? the view/form/model shouldn't save my "custom" fields automatically along with the "core" user info? How do i do that? -
django.core.exceptions.FieldError: Unknown field(s) (custom_field) specified for MyUser
I am trying to use the following command: docker-compose exec web python manage.py makemigrations, but I recieve an error as the title of this question: 'django.core.exceptions.FieldError: Unknown field(s) (custom_field) specified for MyUser'. Thanks for your Help! MyUser is a sub class of the AbstractClass. My code: -----------------------------------------users/models.py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractUser class MyUserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The eMail address you typed in, is already in use.') if not password: raise ValueError('You haven\'t typed in a password.') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, ) user.is_admin = True user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class MyUser(AbstractUser): email = models.EmailField( verbose_name= 'email address', max_length=255, unique=True, ) date_of_birth = models.DateField(verbose_name='birthday') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) nickname = models.CharField(unique=True, max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) nationality = models.CharField(max_length=30) mother_language = models.CharField(max_length=30) father_language = models.CharField(max_length=30) skin_colour = models.CharField(max_length=30) religion = models.CharField(max_length=30) sex = models.CharField(max_length=30) … -
NameError: name 'models' is not defined , help using django custom model
Got no idea what's going on here. First time using a custom user model so I'm having trouble referencing the user object in views. I know I need to use 'get_user_model' , but I'm not sure how to implement it. I tried doing a couple things but I'm still stuck. error = NameError: name 'models' is not defined. It shows up with 'description = models.Profile.objects.get(user=request.user).description' **views.py, part that's giving me an error ** from __future__ import unicode_literals from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth import logout from django.contrib.auth import login, logout, authenticate from dating_app.forms import RegistrationForm,ProfileUpdateForm from .models import Profile from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User import os from django.core import serializers import json from django.contrib.auth import get_user_model User = get_user_model() def mingle(request): try: user = (Profile.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0]) except IndexError: user = None print(User.username) try: description = models.Profile.objects.get(user=request.user).description except models.Profile.DoesNotExist: create = Profile.objects.get_or_create(user = request.user) return redirect('profile') match = models.Profile.objects.get(user=request.user).matches.all() context = dict(user = user, match = match) return render(request, 'dating_app/mingle.html', context) models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager, User from dating_project import settings class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not … -
Dropdown list from an object attribute in Django template
So what I'm trying to do is a dropdown list in a template, this list consists of the attribute of another object in another app, however, I don't seem to know what's going on in the HTML side, since it doesn't show any attributes, it shows nothing. I'm using class based templates and views Here's what I've done so far: project/models.py class Project(models.Model): projectID = models.AutoField(primary_key=True, db_column="Id", db_index=True, verbose_name='Project ID') description = models.CharField(max_length=900) def __str__(self): return str(self.projectID) def get_description(self): return str(self.description) this is the object that should show the dropdown list model pm/models.py: class Pm(models.Model): pmid = models.AutoField(primary_key=True, db_column="Id", db_index=True) pmnumber = models.CharField(max_length=50, unique=True, db_column="pmnumber") description = models.CharField(max_length=600) projectId = models.ForeignKey(Project, on_delete=models.CASCADE, db_column="ProjectID", related_name='+') def __str__(self): return str(f'{self.PMid}, {self.PMNumber}, {self.description}') this is the form pm/forms.py: class PMForm(forms.ModelForm): class Meta: model = Pm fields = ('pmnumber', 'description', 'projectId') and this is the views archive for that model: class CreatePMView(LoginRequiredMixin, CreateView): template_name = 'pm/new.html' form_class = PMForm success_url = reverse_lazy('project:feed') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user'] = self.request.user return context def get_description(self): return self.request.project.description And this is the part of the template where I want to render the description from the project and shows nothing: <select class="form-control"> {% for project in … -
Google Storage + JQuery-File-Upload + Django + Signed URL, how should I change submit() and relevant options?
I have the following js code and it uses the signed-url api to get signed urls for uploading content to google storage via Django api. When I use it with the following code : xhr.open("PUT", data.signed_url); xhr.setRequestHeader('Content-Type', file.type); xhr.send(file); It works fine and I am able to upload to Google Storage very large files. But obviously, when I do that, I cannot use any progress-bar features of jquery-file-upload. Can you please suggest on how I should alter the data.submit(), where shall I put it, and how should I change the options or settings prior to submitting. Should I be overriding add or submit callback ? I feel that there is a missing support for Google Storage with Jquery-file-upload as the only example covers only obsolute Google Blobstore in the following link : https://github.com/blueimp/jQuery-File-Upload/wiki/Google-App-Engine $("#fileupload").fileupload({ dataType: 'json', type: 'PUT', sequentialUploads: true, submit: function(e, data) { var $this = $(this); $.each(data.files, function(index, file) { // pack our data to get signature url var formData = new FormData(); formData.append('filename', file.name); formData.append('type', file.type); formData.append('size', file.size); // Step 3: get our signature URL $.ajax({ url: '/api/getsignedurl/', type: 'POST', processData: false, contentType: false, dataType: 'json', headers: { 'X-CSRFToken': Cookies.get('csrftoken'), }, primary_data: data, data: formData }).done(function (data) … -
Best tool for Django recurrent payments?
I am about to add membership plans to my Django website and I was looking for some feedback. Havent decided between paypal or stripe. What do you guys think? If there are more options I will be happy to know them. Thanks! -
Using materialize how do i center a tabs in nav-content
https://i.imgur.com/JBI7id0.png So basically i am having an issue. I have no problem in moving any of the tabs to the right or left side. But when i try to center all the tabs i'm having no luck. So in the image above i am trying to get DROP ME!, TEST 2, DISABLED TAB AND TEST 4 to be centered on the page. I am using the Extended Navbar with Tabs example on their website. <div class="nav-wrapper"> <a href="/" class="brand-logo" >Skolplattform</a> <a href="#" data-target="mobile-demo" class="sidenav-trigger"><i class="material-icons">X</i></a> <ul id="nav-mobile" class="right hide-on-med-and-down"> {% if user.is_authenticated %} <li><a href="/logout">Logout</a></li> <li><a>{{user.username}}</a></li> {% else %} <li><a class="waves-effect waves-light btn" href="/register">Register</a></li> <li><a class="waves-effect waves-light btn" href="/login">Login</a></li> {% endif %} </ul> </div> <div class="nav-content"> <ul class="tabs tabs-transparent"> <li class="tab"><a class='dropdown-trigger' href='#' data-target='dropdown1'>Drop Me!</a></li> <li class="tab"><a href="#test2">Test 2</a></li> <li class="tab"><a href="#test3">Disabled Tab</a></li> <li class="tab"><a href="#test4">Test 4</a></li> </ul> </div> </nav>``` -
Should I go for AbstractBaseUser or AbstractUser? - Django
I am building a web app with Django where different users can create posts, etc. At the moment I am using the default User model along with a Profile model I created. The default User model is sufficient enough, however, I would like the users to be able to only register with a username made up of integers and I would also like to add my own authentication for when registering a new username. Do you suggest I use the AbstractBaseUser model or the AbstractUser? What is the core differences between these and what would be better in my case? -
How do I adjust my Django serializer to accept an array of a field?
I'm using Django 2.0 and Python 3.7. I have the following models (CoopType is a many-to-many field of Coop) ... class CoopTypeManager(models.Manager): def get_by_natural_key(self, name): return self.get_or_create(name=name)[0] class CoopType(models.Model): name = models.CharField(max_length=200, null=False) objects = CoopTypeManager() class Meta: unique_together = ("name",) class CoopManager(models.Manager): # Look up by coop type def get_by_type(self, type): qset = Coop.objects.filter(type__name=type, enabled=True) return qset # Look up coops by a partial name (case insensitive) def find_by_name(self, partial_name): queryset = Coop.objects.filter(name__icontains=partial_name, enabled=True) print(queryset.query) return queryset # Meant to look up coops case-insensitively by part of a type def contains_type(self, types_arr): filter = Q( *[('type__name__icontains', type) for type in types_arr], _connector=Q.OR ) queryset = Coop.objects.filter(filter, enabled=True) return queryset class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType) #type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() I don't know how to properly create a serializer to accept the inputs. I have these serializers ... class CoopTypeField(serializers.PrimaryKeyRelatedField): queryset = CoopType.objects def to_internal_value(self, data): if type(data) == dict: cooptype, created = CoopType.objects.get_or_create(**data) # Replace the dict with the ID of the newly obtained object data = cooptype.pk return super().to_internal_value(data) ... class CoopSerializer(serializers.ModelSerializer): type = CoopTypeField() address … -
Django hide slug field to users in custom template
I've built a form with auto-generating slug field with short js code. I'd want to hide the slug field to user to prevent them being edited. //slugify.js const titleInput = document.querySelector('input[name=title'); const slugInput = document.querySelector('input[name=slug]'); const slugify = (val) => { return val.toString().toLowerCase().trim() .replace(/&/g, '-and-') // replacing & with '-and-' .replace(/[\s\W-]+/g, '-') //replcaing spaces, non-word chars and dashes with a single '-' }; titleInput.addEventListener('keyup', (e) => { slugInput.setAttribute('value', slugify(titleInput.value)); }); //models.py slug = models.SlugField(max_length=100, unique = True) as I remove it from forms.py, slugfield becomes blank. I know what the problem is, but I don't know how should I fix it. I've tried removing the slugfield from forms.py, but it would just does not add the slug, because I targeted the slug with the input in slugify.js. I've tried editable = False on slugField, but it would give me an error django.core.exceptions.FieldError: 'slug' cannot be specified for VideoPost model form as it is a non-editable field Would there be any other way that I could hide slugfield from the form and properly save the slug as well?