Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django+Haystack+Whoosh, no models being indexed, no results returned in search
I have a haystack search implementation using the whoosh backend in django 1.10. I've followed the "Getting Started" documentation page and have implemented everything I can see there, however, when I run ./manage.py update_index It will show me Indexing 0 posts And when I run a test search I will get no results. I'm creating a forum web app and all the posts are populated with Lorem Ipsum... content. When I search "Lorem" it will not show me any results. settings.py: """ Django settings for portfolio project. Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '...' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'markdown_deux', 'haystack', 'forum', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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 = … -
DJANGO/Heroku not saving into database POSTGRES
I am creating an API and my app isn't saving user information to the POSTGRES database. Can someone look over my code and tell me what is wrong? SECRET_KEY = os.environ['SECRET_KEY'] ALLOWED_HOSTS = ['salty-sands-40947.herokuapp.com','.herokuapp.com'] DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'aroomieapp', 'oauth2_provider', 'social_django', 'social.apps.django_app.default', 'rest_framework_social_oauth2', "push_notifications" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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 = 'aroomie.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', 'django.template.context_processors.media', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'aroomie.wsgi.application' # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation 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', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_REDIRECT_URL = '/' # Setting the image path in server MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # This package help us to replace our database with Postgresql import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) AUTHENTICATION_BACKENDS = ( # Others auth providers (e.g. Google, OpenId, etc) # … -
Django model serialization only returns primary key for foreign key
I'm trying to serialize my model to JSON to be passed to a JavaScript function. When I serialize the model it returns everything fine except for the foreign keys. They return the numeric primary key in the JSON. models.py class NameManager(models.Manager): def get_by_natural_key(self, first_name, middle_name, last_name): return self.get( first_name=first_name, middle_name=middle_name, last_name=last_name) class Name(models.Model): """Name model - contains properties for Name""" objects = NameManager() first_name = models.CharField(max_length=200) middle_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) def natural_key(self): return(self.first_name, self.middle_name, self.last_name,) class Meta: unique_together = (( 'first_name', 'middle_name', 'last_name'),) class SponsorManager(models.Manager): def get_by_natural_key(self, sponsor_name, sponsor_email, sponsor_phone, sponsor_address): return self.get( sponsor_name=sponsor_name, sponsor_email=sponsor_email, sponsor_phone=sponsor_phone, sponsor_address=sponsor_address) class Sponsor(models.Model): """Sponser model - contains properties for Sponsor""" objects = SponsorManager() sponsor_name = models.ForeignKey(Name) sponsor_email = models.EmailField(default='Please enter') sponsor_phone = models.IntegerField(default=0000000) sponsor_address = models.ForeignKey(Address) def natural_key(self): return(self.sponsor_name, self.sponsor_email, self.sponsor_phone, self.sponsor_address) class Show(models.Model): """Show model - contains properties for Shows""" BOX_CHOICES = ( ('box', 'BOX'), ('gred', 'GRED'), ('boxgred', 'BOX/GRED')) show_date = models.DateField() show_time = models.TimeField(default=datetime.now()) show_type = models.CharField( choices=BOX_CHOICES, default='box', max_length=8) show_box_total = models.IntegerField(default=0) show_address = models.ForeignKey( Address, related_name='show_address') show_sponsor = models.ForeignKey( Sponsor, default=1, related_name='show_sponser') views.py def dashboard_view(request): """render the admin view""" get_all_shows = Show.objects.all().order_by('show_date') json_shows = serializers.serialize('json', get_all_shows) print (json_shows) context = { 'json_shows': json_shows } return render( request, 'website/dashboard_view.html', … -
Django: combining method and class inside views to share same url
I'm working on Django project where I have an app which has a page with a drop down and a chart that is generated from data (which is queried from the database and passed into an API url). I'm using class based views and APIView and have a get method which is creating a response to pass some Json data into a url. I have the following class in my views.py set up and working. views.py class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): data =#code to generate data via query goes here return Response(data) In order have access to this data, I have my url set as: url(r'^display/api/chart/data/$', views.ChartData.as_view()), This data from the API is used to generate a ChartJS graph in my template html of this app. The chart is set up so that it seeks the Json data from the url display/api/chart/data/ and uses Ajax to populate itself. I also have another method in the same views file as follows: views.py def DropdownDisplay(request): items= #query from database if (request.method == 'POST' and request.is_ajax()): print(request.POST) return render(request, 'DisplayData/Display.html',{'dropdown':items}) This method is used to generate a dropdown in the page. The url for this is … -
Django 1.4 - query iteration using fields stored in a dictionary
I had a huge registration table with 112 fields. For a particular search I want to compare 17 fields & assign colors to variable say 'clrSelected'. My code is : reg = Regisration.objects.filter('some condition').order_by("name") for r in reg: if r.name=='abc': clrSelected='#fff' if r.type=='1': clrSelected='#000' if r.appl=='10': clrSelected='#c1ff51' if r.code=='': clrSelected='#60c5f7' if r.qlty=='first': clrSelected='#f99334' ... ... I want to access the field name from a dictionary like this flds = {'1':'name', '2':'type', '3':'appl', '4':'code', '5':'qlty',...} And use it something like this if r.flds['1']=='abc': clrSelected='#fff' if r.flds['2']=='1': clrSelected='#000' ... How could i use the fields as above. I am using django 1.4 & python 2.7 -
How to set specified kwargs to url outside for loop?
I have some links in template. <ul> {% for cat in cats %} <li><a href="{% url 'c_index' cat.slug %}">{{ cat.name }}</a> {% endear %} </ul> <ul> {% for type in types %} <li><a href="{% url 'ct_index' cat.slug type.slug %}">{{ type.name }}</a> {% endear %} </ul> Of course, I can't access second link because I can't use 'cat.slug' outside {% for cat in cats %} loop. But I want to set "cat.slug" to second link without using {% for cat in cats %} loop. How can I do this? For example, using template tag? -
xampp_MYSQL_when i connect databse to my PhpMyAdmin and my database in there? this error message appear how i solve it
Object not found! The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error. If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/7.1.1 -
Does Django require the full web-setup to run professionally on non-internet devices?
This is either a really good or really stupid question, but I find its worth asking -- I'm making a Django app that runs on a device as an interfaces. Is there any reason to think I could just use the python manage.py runserver and go no further? Or is there a better way to do this? Installing the full web-bundle for local-network-devices seems excessive, hence my question. (Perhaps there is not a great deal of overhead using the full-web-setup -- I dunno). This is currently on the Raspberry pi, but for prototype purposes. The end-product will not necessarily be Pi. -
Django, how edit comments?
I have table with games. I wrote Comment models and I can add comments to the games, but I can't edit them. I try many times, once accidentally I edited one comment (if there was more - error about get only one argument), but I have no idea how. Comment models: class Comment(models.Model): game = models.ForeignKey(Games) author = models.ForeignKey(User) content = models.TextField(max_length=400) date_of_published = models.DateTimeField() View with comment adding: def add_comment(request, game_id): g = Games.objects.get(id = game_id) if request.method == "POST": cf = CommentForm(request.POST) if cf.is_valid(): comment = cf.save(commit=False) comment.date_of_published = timezone.now() comment.author = request.user comment.game = g comment.save() return HttpResponseRedirect('/games/%s' % game_id) else: cf = CommentForm() args = {} args.update(csrf(request)) args['game'] = g args['form'] = cf return render(request, 'add_comment.html', args) urls : url(r'^(?P<game_id>\d+)/$', views.game), url(r'^(?P<game_id>\d+)/add_comment/$', views.add_comment), url(r'^(?P<game_id>\d+)/add_comment/edit/$', views.edit_comment), template add_comment: <form action="/games/{{game.id}}/add_comment/" method="post" class="form horizontal well"> {% csrf_token %} {{form.as_p }} <input type = "submit" class="btn btn-inverse" name="submit" value="Add Comment"/> </form> template edit.html <h1>Edit comment</h1> <form action="/games/{{game.id}}/add_comment/edit/" method="post" class="form horizontal well"> {% csrf_token %} {{form.as_p }} <input type = "submit" class="btn btn-inverse" name="submit" value="Asd Comment"/> </form> How make edit_comment? Please help. -
Changing primary_key to Django AbstractBaseUser model
I have this custom User model in which I've changed the primary_key to email field like so: class User(AbstractBaseUser, PermissionsMixin): # Primary Key of my model email = models.EmailField(max_length=254, primary_key=True) username = models.CharField(_('username'),max_length=30, unique=True, help_text=_('Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[ RegexValidator( r'^[\w.ñ@+-]+$', _('Enter a valid username. This value may contain only ' 'letters, numbers ' 'and @/./+/-/_ characters.') ), ], error_messages={ 'unique': _("A user with that username already exists."), }, ) first_name = models.CharField(max_length=50,blank=True, null=True, ) last_name=models.CharField(max_length=50, blank=True, null=True,) is_staff = models.BooleanField( default=True, help_text='Designates whether the user can log into this admin site.') is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() I also have another model named Match: class Match(models.Model): match_date = models.DateTimeField(default=timezone.now, null=True) home_team_players_accept = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='home_team_players_accept', blank=True,) away_team_players_accept = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='away_team_players_accept', blank=True,) home_team_players_cancel = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='home_team_players_cancel', blank=True,) away_team_players_cancel = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='away_team_players_cancel', blank=True,) fichaje_players_match = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='fichaje_players_match', blank=True,) When I execute python manage.py migrate I get this output: File "/home/bgarcial/.virtualenvs/fuupbol2/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.InternalError: cannot drop constraint auth_user_pkey on table auth_user because other objects depend on it DETAIL: constraint auth_user_groups_user_id_6a12ed8b_fk_auth_user_username on table auth_user_groups depends on index auth_user_pkey constraint … -
How in template show button if object are empty?
Can someone say where I did mistake? I have 2 models: Project and Purpose. class Purpose(models.Model): code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False) project = models.ForeignKey(Project, on_delete=models.CASCADE) text = models.TextField(_('Text')) comments = models.ManyToManyField("Comment") Every project has only one purpose. So in project_detail page I want to show purpose_add button only if that project dont have any other purpose object. Why I dont see button when there is no Purpose object with the same project_code? views.py: def project_detail(request, project_code): *** purpose_is_not_exist = Purpose.objects.exclude(project=project_code).exists() *** project_detail.html: {% if purpose_is_not_exist %} <button id="purpose-add-button"></button> {% endif %} -
No patterns or invalid patterns
Here are my files: urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^prediction/', include('prediction.urls')) ] prediction/urls.py urlPatterns = [ url(r'^$', views.post_list, name='post_list') ] View.py def post_list(request): return HttpResponse('Hello') I'm receving an error saying that prediction/urls.py does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I've cross checked multiple sources and documentations. I know this is a basic question, but I just can't seem to spot any syntax or possibly regex mistake that's producing this error. -
how to run a RequestFactory.get test
Hi I want to Test the Detail view. I'm providing an pk but the test keep failing. def test_detail_view(self): request = RequestFactory().get('portail/detail/') response = ArtefactDetailView.as_view()(request, pk=12252) self.assertEqual(response.status_code, 200) error def test_detail_view(self): request = RequestFactory().get('portail/detail/') > response = ArtefactDetailView.as_view()(request, pk=12252) applications\portail\tests\test_requests.py:37: E django.http.response.Http404: No Artefact found matching the query . -
oauth2_provider.models.DoesNotExist: AccessToken matching query does not exist. Heroku
I am running into an issue with my heroku application which is supposed to be an API for my iOS application. Currently, I am able to sign in with Facebook into my application but it does not save any of the information. It has been giving me this error: 2017-04-27T00:54:53.549525+00:00 heroku[router]: at=info method=GET path="/api/user/profile/?access_token=" host=salty-sands-40947.herokuapp.com request_id=32102365-2dca-4af3-aa83-0772349e6554 fwd="70.214.100.250" dyno=web.1 connect=1ms service=99ms status=500 bytes=69771 protocol=https 2017-04-27T00:54:53.489472+00:00 app[web.1]: Internal Server Error: /api/user/profile/ 2017-04-27T00:54:53.489488+00:00 app[web.1]: Traceback (most recent call last): 2017-04-27T00:54:53.489490+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner 2017-04-27T00:54:53.489490+00:00 app[web.1]: response = get_response(request) 2017-04-27T00:54:53.489491+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response 2017-04-27T00:54:53.489492+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2017-04-27T00:54:53.489493+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response 2017-04-27T00:54:53.489494+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2017-04-27T00:54:53.489495+00:00 app[web.1]: File "/app/aroomieapp/apis.py", line 60, in user_get_profile 2017-04-27T00:54:53.489495+00:00 app[web.1]: expires__gt = timezone.now()) 2017-04-27T00:54:53.489496+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method 2017-04-27T00:54:53.489497+00:00 app[web.1]: return getattr(self.get_queryset(), name)(*args, **kwargs) 2017-04-27T00:54:53.489497+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/db/models/query.py", line 385, in get 2017-04-27T00:54:53.489498+00:00 app[web.1]: self.model._meta.object_name 2017-04-27T00:54:53.489499+00:00 app[web.1]: oauth2_provider.models.DoesNotExist: AccessToken matching I am using heroku. I hope someone can point me into the right direction. Thank you -
django-registratio-redux - password_reset_email.html
I have searched everywhere and can not find an answer. I am using django-registration-redux 1.5 with django, I have my templates in the templates folder, but specifically the file "password_reset_email.html" does not load html when I send it, the file to activate the account does load the html correctly. Thank you -
Django floppy forms error
When I run this code on my django website I have this error: Code --> http://django-floppyforms.readthedocs.io/en/latest/usage.html#forms from the usage of floppyforms. Error: htt//a//ps://i.stack.imgur.com/w3sQr.png remove //a// from link How can i fix it? My view.py def get_name(request): form = ProfileForm() return render(request, 'personal/code.html', {'form': form}) My code.html <form method="post" action="/some-action/"> {% csrf_token %} {{ form.as_p }} <p><input type="submit" value="Yay!"></p> </form> and forms.py import floppyforms as forms class ProfileForm(forms.Form): name = forms.CharField() email = forms.EmailField() url = forms.URLField() -
Another drop down menu
Here is my .html file : {% load i18n %} <div class="customer-context-menu closed {% if customer.gender == 0 %}male{% else %}female{% endif %}"> <b class="unselectable"> {{ customer.icon }} {{ user.get_full_name }} </b> <ul> <li class="tip"></li> <li><a href="{% url "customers:perceptions" cust=customer.pk %}" class="unselectable" data-turbolinks="false">{% trans "Perceptions" %}</a></li> <li><a href="{% url "customers:profile" cust=customer.pk %}" class="unselectable" data-turbolinks="false">{% trans "Profile" %}</a></li> <li><a href="{% url "customers:alerts_index" cust=customer.pk %}" class="unselectable" data-turbolinks="false">{% trans "Alerts" %}</a></li> <li><a href="{% url "customers:messaging" cust=customer.pk %}" class="unselectable" data-turbolinks="false">{% trans "Messaging" %}</a></li> <li><a href="{% url "customers:requests" cust=customer.pk %}" class="unselectable" data-turbolinks="false">{% trans "Requests" %}</a></li> <li><a href="{% url "customers:documents" cust=customer.pk %}" class="unselectable" data-turbolinks="false">{% trans "Documents" %}</a></li> <li><a href="{% url "customers:logs" cust=customer.pk %}" class="unselectable" data-turbolinks="false">{% trans "Logs" %}</a></li> <li class="separator"></li> <li><a href="{% url "customers:loan" cust=customer.pk pk=loan.pk%}" class="unselectable" data-turbolinks="false">{% trans "Loan" %}</a></li> <li class="separator"></li> {% if customer.phone_1 %} <li class="phone">{{ customer.phone_1 }}</li> {% endif %} <li><a href="mailto:{{ user.email }}" data-turbolinks="false"><i class="material-icons">email</i> {{ user.email }}</a></li> <li><a href="{% url "customers:print" cust=customer.pk %}" class="unselectable" data-turbolinks="false" target="_blank"><i class="material-icons">printer</i> {% trans "Print" %}</a></li> </ul> </div> I would like it could give me the drop down menu I drew. Here is the the result including my drawing : drawing Could anyone have time to show me how I could do such thing here? … -
How to implement notification service using Django Channels in a chat application?
I am working on chat application based on django, but for real time notifications and chatting, I plan on using django channels. The problem is that apart from documentation there are hardly any resources available to get in-dept knowledge of the concepts. Can anyone suggest a way to implement notifications in my application as when a user receives a message, he/she gets notified(using websockets concept). Also, I plan on using channels as a way to display which of the users are currently online. Models are as follows : class Person(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=50) contact = models.CharField(max_length=12) online = models.IntegerField(default=0) def __str__(self): return self.name class Dialog(models.Model): author = models.ForeignKey(Person,related_name="self") reader = models.ForeignKey(Person) def __str__(self): return self.author.name + " - " + self.reader.name class Message(models.Model): dialog = models.ForeignKey(Dialog) sender = models.ForeignKey(Person) text = models.TextField() def __str__(self): return self.sender.name + " : " + self.text I have been stuck with this problem for a while now. I would be grateful if anyone can suggest a solution. Thanks in advance. -
Django logout ValueError
I have a ValueError at logout in Django. It says: The view django.contrib.auth.logout didn't return an HttpResponse object. It returned None instead. My code is extremely short: def logout_view(request): logout(request) return HttpResponseRedirect('/some_page/') I tried with shortcut redirect as well. Probably I misunderstand how this works. -
Django Oauth Toolkit Invalid Credentials With Special Characters
I am using Django Oauth Toolkit with DRF. When authenticating, Django Oauth Toolkit works successfully when there are no special characters in the username. However when a special character exists, the authentication fails. The documentation explicitly states the username can contain special characters. url = 'http://myurl.com/o/token' data1 = { 'username': 'asdf', 'password': 'asdf', 'grant_type': 'password', 'scope': 'read' } data2 = { 'username': 'asdf@asdf', 'password': 'asdf', 'grant_type': 'password', 'scope': 'read' } headers = { 'content-type': 'application/json', } auth = ( 'client_id', 'clietn_secret' ) user = User.objects.get(username='asdf') # returns object user2 = User.objects.get(username='asdf@asdf') #returns object response1 = requests.post(url, data=json.dumps(data1), headers=headers, auth=auth) #returns 200 response2 = requests.post(url, data=json.dumps(data2), headers=headers, auth=auth) #returns 401 '{"error_description": "Invalid credentials given.", "error": "invalid_grant"}' I have tried: Removing all special characters when creating the account, then removing the special characters when logging in Using client_credentials for the scope Using re.escape for both registering and logging in Using urllib.quote for both registering and logging in I must be missing some fundamental concept. Why does creating a new Django user with a username containing a special character affect OAuth? Is there a workflow to create accounts and then authenticating them when using special characters? -
Django rest PageNumber Pagination
I have a simple Pagination class of the django rest framework: class StandardResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 1000 # Create your views here. class ResultSet(generics.ListAPIView): queryset = Result.objects.all() serializer_class = ResultSetSerializer pagination_class = StandardResultsSetPagination This class currently returns a dict with 'prev' and 'next' keys that contains a URL with the next page and prev page. What I would like to achieve is that the 'prev' and 'next' return just the page number instead of the whole URL. How can I achieve this? -
How to incorporate Golang in to your website?
I have a website that uses django and an sql database. I want to use Golang with my website i don't know any way to incorporate. I want it to accelerate my performance in the website because i have some of my "parts" (ex. Like Login and Follow its a music site) that are very cpu intensive and need to be optimized a better way. Please Help me. -
Django- Problems with like/follow button's
I want to create a like/follow system on user posts. Due to many users being able to like a post and users being able to like many posts I made 2 separate models. Models.py: class Question(models.Model): user= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.TextField() content = models.TextField() date_published = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(_('Last Edited'), auto_now=True) slug = models.SlugField(max_length=255) class Question_Follows(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) count = models.IntegerField(default=0) views.py class QuestionDetailView(DetailView): model = Question slug = 'slug' template_name = "questions/question_detail.html" def get_context_data(self, **kwargs): context = super(QuestionDetailView, self).get_context_data(**kwargs) context['now'] = timezone.now() #obj= Question_Follows.objects.filter(id=question.id) #context['follow_count'] = Question_Follows.objects.filter(id='question.id') #obj.count <----- none of these have worked so far. return context detailview.html: <div id="question_container"> <input type='hidden' id="{{ object.id }}" name="id"> <--- tried this as a way to get question id --> <h1>{{ object.title }}</h1> <p>{{ object.content }}</p> <p>Published: {{ object.date_published|date }}</p> <p>Date: {{ now |date }}</p> <button class="follow"><span id='follow-span'>Follow| <strong id='follow-count'>{{ follow_count }}</strong> </button> </span></button> I'm having problems 'collecting' the right question once the like button has been pressed and also showing the right number of likes for the question i.e the follow count for each question. -
how to properly refactor this function into another file? django
I have a try and except which is used super often, so I am thinking of taking it out and make it into a function in other file but I cannot seem to make it work. Can someone please give me a hand? this is the code which I use really really often try: user = get_object_or_404(User, email=data['email']) except Exception as e: print(e) return json_response_message(False, e.message) I tried making it into another file and did it this way def auth_token(data): try: return get_object_or_404(User, email=data['email']) except Exception as e: return JSONresponse({'status': False}) then when I call auth_token I did it this way in another way and of course I did import it user = auth_token(data) I can understand this would then return me JSONresponse({'status': False}) and I tried using raise and it would tell me that I can't use JSONresponse Can someone give me an idea how this can be done? -
Django forms validating boolean values and numbers as string
I have a form as shown below, class UserForm(forms.ModelForm): name = forms.CharField(max_length=255) tagline = forms.CharField(max_length=255) privacy = forms.CharField(max_length=10) description = forms.CharField(max_length=2000) home_id = forms.CharField(max_length=32, required=False) class Meta: model = User fields = ['name', 'tagline', 'privacy', 'description'] and when I pass any field as a boolean or numerical value (say, name=True) , the form validates it form.is_valid returns True while if I skip one field (say name=None), the form says the form is invalid. The form works, but not for a boolean value for any field. Form also validates correctly for floats, lists and dicts. What am I doing wrong? The same happens for a form.Form without mentioning a model.