Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript included in base.html doesn't work in extending template
I have the following project file structure: In base.html, I'm importing some JS that is meant to add an onclick event to the button in the html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Default Title{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/workoutcal.css' %}"> </head> <body> {% block userwidget %} <button type="button" id="logoutbutton">Logout</button> {% endblock %} {% block content %}{% endblock %} {% block footer %}{% endblock %} <script type="text/javascript" src="{% static "js/base.js" %}"></script> </body> </html> base.js: logoutbutton = document.getElementById("logoutbutton"); logoutbutton.onclick = logout; function logout(){ window.location = "/workoutcal/logout"; } Then, in calendar.html: {% extends "workout/base.html" %} {% block title %}{{ title }}{% endblock %} The button shows up in the browser, but when I click it, nothing happens. From the browser console I get these errors: GET http://localhost:8000/static/js/base.js net::ERR_ABORTED localhost/:359 GET http://localhost:8000/static/js/base.js 404 (Not Found) Sto the static files are obviously not found. Am I doing something wrong? -
How to change the option values with django-autocomplete-light?
I use django-autocomplete-light in a fairly standard way, simply following the tutorial on http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html. Whenever I use the Select2 widget, however, the values of the options are automatically the primary keys of the model instances. Is there a way to use set the value to another field of the model? -
Django social auth how to access authenticated user data in template
I have implemented django social auth in my project which is working fine, Now i want to display authenticated user's data in header template. what is the proper way to do that? One way i think might be context_processors but how can i access "extra_data" in social responce, like gender and phone? -
"OSError: mysql_config not found" when trying to "pip install mysqlclient" - Django
I'm relatively new to Django, and Web Development in general. I am trying to pip install mysqlclient in my virtualenv -p python3 to hook up Django 2.0 to mySQL. However, I'm getting this error: Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/43/md5vpqrx0mx8627sq04slbz00000gn/T/pip-build-l8ea3vja/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/43/md5vpqrx0mx8627sq04slbz00000gn/T/pip-build-l8ea3vja/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/43/md5vpqrx0mx8627sq04slbz00000gn/T/pip-build-l8ea3vja/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/43/md5vpqrx0mx8627sq04slbz00000gn/T/pip-build-l8ea3vja/mysqlclient/ I have looked around for answers for hours, and yes, I have checked out this and this but nothing seems to be working. Any help would be much appreciated! -
Unable to install Django in my mac - Command "python setup.py egg_info" failed with error code 1
I tried to install Django using sudo pip install Django command. It has downloaded but got stuck to error - Command "python setup.py egg_info" failed with error code 1. Terminal I've installed Python 3.6.3, but pip still pointing to Python 2.7, is above issue occurs because of pip not pointing to python 3.6.3? Terminal -
custom django form template (in bootstrap)
I would like to customize my django forms. For example, in my code I have working hour settings which I like to produce like this format: mon_start mon_end tue_start tue_end .... but instead it creates a form mon_start mon_end tue_start tue_end .... Here is a view of the output that I dont want https://imgur.com/a/cPxTW Below are my code: forms.py class CompanyWorkingHoursSettingsForm(forms.ModelForm): mon_start = forms.TimeField() mon_end = forms.TimeField() tue_start = forms.TimeField() tue_end = forms.TimeField() class Meta: model = Workinghours fields = ("mon_start","mon_end","tue_start","tue_end") workinghourssettings.html {% extends 'project/base.html' %} {% load bootstrap3 %} {% block page %} <div class="col-lg-12"> <div class="panel"> <div class="panel-heading bg-blue"> <h4 class="panel-title text-center text-white"> Working Hours Settings </h4> </div> <div class="panel-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form company_workinghourssettings_form %} <button type="submit" class="btn btn-pink">Update</button> </form> </div> </div> </div> {% endblock %} How do i produce a custom arranged form for my form fields above ? (in bootstrap) -
TypeError: export_users_xls() missing 1 required positional argument: 'request'
when I am trying to run i got this error File "/home/normsoftware/WORK/JVB/healthtracker/quicklook/urls.py", line 39, in <module> url(r'^users/print$',views.export_users_xls(),name="Exceldata"), TypeError: export_users_xls() missing 1 required positional argument: 'request' views.py def export_users_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="users.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Users') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['first', 'last',] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Registration.objects.all().values_list('first', 'last') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response all line indentations are correct urls.py url(r'^users/print$',views.export_users_xls(),name="Exceldata"), -
Database Value in PDF Django
How can i display my data in database and export it to pdf -Django? my x variable is getting all the data in my database, i guess? someone help me how can i display all data and export it to pdf file. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="WishList.pdf"' buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer) x = Item.objects.all() p.drawString(100, 100,x) p.drawString(200,300,"bills") # Close the PDF object cleanly. p.showPage() p.save() # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) return response -
Problems with Many to Many relationships in Django REST-framework
I am having some problems with the Many to Many relationships in Django. When you have a fresh setup of a Django REST framework app, you usually have two default models: Users and Groups. From within the web interface you can create groups. After doing this you will also be able to select an existing Group from a list to add to a user. Like so: http://prntscr.com/hp2lu0 Now when I try to do something like this myself, I get the following in my web-interface: Lists are not currently supported in HTML input.: http://prntscr.com/hp2pe5 Why does it work for Groups but not when I try do it myself? These are the models im trying to get it to work with: class Ip(models.Model): address = models.CharField(max_length=100) @classmethod def create(cls, address): ip = cls(address=address) # do something with the ip return ip class IpCollection(models.Model): title = models.CharField(max_length=100) ipAddresses = models.ManyToManyField(Ip) @classmethod def create(cls, title): ipCollection = cls(title=title) # do something with the ipCollection return ipCollection And this is how my serializers look like: class IpSerializer(serializers.ModelSerializer): class Meta: model = Ip fields = ('address',) class IpCollectionSerializer(serializers.Serializer): title = serializers.CharField(max_length=200) ipAddresses = IpSerializer(read_only=False, many=True) def create(self, validated_data): """ Create and return a new `IpCollection` instance, … -
How to get manytomanyfield model datas in View in Django
models.py class Account(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE, default='auth.User') id = models.CharField(max_length=50, unique=True) pw = models.CharField(max_length=200) nick = models.CharField(max_length=50, blank=True) blog = models.URLField(null=True, blank=True) published_date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.published_date = timezone.now() self.pw = make_password(self.pw) super(Account, self).save(*args, **kwargs) def __str__(self): return self.id class Meta: ordering = ["-published_date"] class Task(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE, default='auth.User') account = models.ManyToManyField(Account) published_date = models.DateTimeField(default=timezone.now) def publish(self): self.published_date = timezone.now() self.save() forms.py classAccountForm(forms.ModelForm): class Meta: model = NaverAccount fields = ('id', 'pw', 'nick','blog',) class TaskForm(forms.ModelForm): class Meta: model = Task fields = ('account',) task.html <form action="#" class="form-horizontal" method="POST"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success" type="submit">Save</button> views.py def task(request): if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() #1. id = str(from Account model) #2. pw = str(from Account model) post.save() form.save_m2m() return redirect('task') else: form = TaskForm() context = {'form': form} return render(request, 'work/task.html', context) I'm making small task app. I want to get model datas that user select(Account) from template in view. ex) user can select 'id1', 'id2'. and i want to get id, pw value in view. so i can play small task with using id, pw in view i … -
Logger in Django project sends messages at sentry and console at the same time
I have this LOGGING setting in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'django.utils.log.NullHandler', }, 'sentry': { 'level': 'DEBUG', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', }, 'logfile': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(TELESPINE_ROOT, 'logs', 'server.log'), 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': ['console', 'sentry'], 'propagate': True, 'level': 'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'project': { 'handlers': ['console', 'logfile', 'sentry'], 'level': 'DEBUG', }, 'sockets_server': { 'handlers': ['console', 'sentry'], 'level': 'INFO', }, } } And I also have this in the file with websocket server: logger = logging.getLogger('sockets_server') application.listen(3000) logger.info('WebSockets server started on 3000') Why do I always get not just console but also Sentry messages in my console while running sockets_server file. Instead of just getting this: [18/Dec/2017 11:50:47] INFO [sockets_server:149] WebSockets server started on 3000 I also get this: ERROR:sentry.errors.uncaught:[u'WebSockets server started on 3000'] And why this message is shown as error? It has just info level -
django xadmin not compatible with Multiselectfield
'''I wanna use Multiselefield module in xadmin to get multible checkboxs. But it is still dropdown option which only can choose one option and can't update to database. However Multiselectfield is no problem used in admin. It can update and show in the list_display while xadmin can't! How to resolve this issue in xadmin? admin: [enter image description here][1] [enter image description here][2] xadmin: [enter image description here][3] ''' model.py class RoomBooking(models.Model): ROOM_CHOICE = ( (1, 'Room1'), (2, 'Room2'), (3, 'Room3'), (4, 'Room4'), (5, 'Room5'), (6, 'Room6'), ) roomNumber = models.CharField(max_length=5, verbose_name=u'会议室', blank=True, null=True) roomStatus = models.CharField(max_length=10, verbose_name=u'会议室号状态', choices=(('occupied', '占用'), ( 'reserved', '预定'), ('available', '可用')), blank=True, null=True) roomUser = MultiSelectField(verbose_name=u'会议室使用者', choices=ROOM_CHOICE, default='1,3,5', blank=True, null=True) class Meta: verbose_name = u'会议室管理' verbose_name_plural = verbose_name form.py from django import forms from .models import RoomBooking class RoomBookingForm(forms.ModelForm): ROOM_CHOICE = RoomBooking.ROOM_CHOICE roomUser = forms.MultipleChoiceField(`enter code here` required=False, label='会议室', widget=forms.CheckboxSelectMultiple(), choices=ROOM_CHOICE, ) class Meta: model = RoomBooking exclude = ['roomNumber', 'roomStatus', 'roomUser'] adminx.py import xadmin from django import forms from .models import RoomBooking from .form import RoomBookingForm from xadmin.filters import format_html class RoomBookingAdmin(object): # form = RoomBookingForm list_filter = ['roomNumber', 'roomStatus'] search_fields = ['roomNumber', 'roomStatus'] list_editable = ['roomNumber', 'roomStatus', 'roomUser'] def has_delete_permission(*args, **kwargs): return False list_display … -
How do I correctly create a related object overriding the save() method?
I'm overriding the save() method on a subclass of a UserCreationForm. I'm doing so because I'd like to create another related object as the User object is created. Here is the form along with the save method: class MyUserCreationForm(UserCreationForm): error_message = UserCreationForm.error_messages.update({ 'duplicate_username': 'This username has already been taken.' }) class Meta(UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) def save(self, commit=True): user = super(MyUserCreationForm, self).save(commit=False) if commit: user.save() Profile.objects.create(user=user) return user So the Profile object is never created. I can get it to work, technically, if I remove the if commit: like so: def save(self, commit=True): user = super(MyUserCreationForm, self).save(commit=False) user.save() Profile.objects.create(user=user) return user However I'd like to know why False is being passed to the save() method each time I create a User. Based on what I've read, the conditional should be there in order to preserve the same behavior as the overridden save() method. -
Django template language - Python array with Javascript index
Well, maybe this is a silly question, but i couldn't find the answer so far. So, i am rendering a view in Django (i will do the code generic to make the problem easier), and the python side looks something like this: ... marray = [1, 2, 3, 4, 5] ... return render(request, "template.html", {"marray": marray}) Now, in the template.html file, I want to access the array, but the index must be determined by a JavaScript variable: var index = 2; var mvar = {{ marray.index }}; console.log(mvar); Output wanted: 3 Obviously, the previous code does not work, it's just to show what I want. Any suggestions? Thanks. -
AWS Cloud9 LinkedIn Authentication django
I have a project in AWS cloud9 when i tryed to do LinkedIn Authentication.(I used this guide - https://realpython.com/blog/python/linkedin-social-authentication-in-django/ and ran a server in port 8080) I added to my linkedin App the URL - http://127.0.0.1:8080/complete/linkedin-oauth2/ - to the field - 'Authorized Redirect URLs:' - in the 'OAuth 2.0'. When I ran the commend 'python manage.py runserver 127.0.0.1:8080' the server started running and open in random url when I tried to login by LinkedIn I got this error myError -
django and ajax - data not returning list values
The ajax request is sent when a user clicks a navigation bar list element. It redirects after the request is processed. The value I am trying to send is an array of an array. I get the data to return a list and print it in the terminal in django. It always shows a list that is empty. views.py @csrf_exempt def color_pick_stats(request): if request.method == 'POST': colors_lst = request.POST.getlist('colors') print(colors_lst) return render(request, 'stats/statistics.html') if request.method == 'GET': return render(request, 'stats/statistics.html') html <li class="list-element"><a href="{% url 'statistics' %}" style="text-decoration: none; color: white;"><span onclick="sendData()">Statistics</span></a></li> javascript function sendData() { $.ajax({ url: '', type: 'POST', data: { colors: color_pick }, success: () => { console.log('success'); }, error: (xhr,errmsg,err) => { console.log(xhr.status + ": " + xhr.responseText); } }) } When I alert the values of the list color_pick in javascript it gives the correct values. In django when printed in terminal the values do not return and the list is returned as empty. Thanks in advance. -
Form resubmission Django how to avoid for refresh or back button
I hava a django application. It is a form to fill (like answered 5 questions clicked next button and go to next five questions). All steps with questions are rendered within 1 view and 1 html file. If I click about_us or other link (to another view and html file), then back button click is followed with "Form resubmission required" and filling from the very beginning required. How to turn back strictly to the previous place. View render template with the next code. @secure_required def presubmit(request): if request.user.is_authenticated(): profile = request.user.profile try: profile.vodID = dictresponse['soap:Envelope']['soap:Body']['InitiateVOAResponse']['VOD_ID'] except: profile.vodID = '' profile.save() lo = {} try: lo_user = User.objects.get(email=request.user.profile.loanOfficer) lo_obj = LoanManager.objects.get(user=lo_user) lo['isChosen'] = True lo['name'] = lo_obj.user.profile.firstName + ' '+lo_obj.user.profile.lastName lo['email'] = request.user.profile.loanOfficer lo['nmlsID'] = lo_obj.nmlsID lo['phone'] = lo_obj.phone except: lo['isChosen'] = False load = False try: preapp = PreApp.objects.filter(username=request.user.username).order_by('-id')[0] load = True except: pass return render_to_response('home/revisedVersion.html', {'user': request.user, 'lo':lo, 'accountcheckURL': accountcheckURL,'load':load}, context_instance=RequestContext(request)) return render_to_response('home/revisedVersionSignup.html', {'user': User.objects.get(email='test9@gmail.com')}, context_instance=RequestContext(request)) revisedVersionSignup has redirect back to this page if user is authenticated and did npt logged out at intermediate steps -
Django widgets - add class to field
I am trying to add class to my inputs in django ModelForm like this: from django import forms from .models import OrderProject class OrderProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrderProjectForm, self).__init__(*args, **kwargs) for field in self.fields: if field.widget.__class__ == forms.widgets.TextInput: if 'class' in field.widget.attrs: field.widget.attrs['class'] += 'project-form__input' else: field.widget.attrs.update({'class':'project-form__input'}) class Meta: model = OrderProject fields = ('name', 'customer', 'area', 'status', 'budget', 'opening_date', 'ending_date',) Unfortunately I got error: 'str' object has no attribute 'widget' Any ideas what I am doing wrong ? -
error while importing a channel route
I am trying to build a chat app using django channels .I ran into this error and can't manage to solve it. raise ImproperlyConfigured("Cannot import channel routing %r: %s" % (routing, e)) django.core.exceptions.ImproperlyConfigured: Cannot import channel routing 'flamingo.routing.channel_routing': 'module' object has no attribute 'channel_routing here is my settings.py file import os 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.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! >SECRET_KEY = '=ee2q)ew^@d(6v$3+@dt#jm9j@6eck-*+fu#b(v$to1dspe&l-' # 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', 'channels', 'chat', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'flamingo.urls' redis_host = os.environ.get('REDIS_HOST', 'localhost') # Channel layer definitions # http://channels.readthedocs.org/en/latest/deploying.html#setting-up-a-channel-backend CHANNEL_LAYERS = { "default": { # This example app uses the Redis channel layer implementation asgi_redis "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [(redis_host, 6379)], }, "ROUTING": "flamingo.routing.channel_routing", }, } 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', ], }, }, ] WSGI_APPLICATION = 'flamingo.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
Django social auth with default AUTH_USER_MODEL
I am new in django and want to implement custom django social auth such that pick username and email from social site and create and save AUTH_USER_MODEL like: from django.contrib.auth.models import User random_passward = generate random passward user = User.objects.create_user( username = social.username, email = social.email, password = random_passward) //send random_passward via email send_mail(...) user.save() what will be the exact implementation and where should i place this code? Thanks in advance -
Return data (one latest object) from all the symbols passed as a list to query
I have a query like EquityIntradayData.objects.using('marketdata').filter(symbol__in=symbol_list).order_by('-date_time')[:1] the return response is like: [ { "close": "591.00000", "symbol": "MPSLTD" } ] I am filtering on a list of symbols symbol_list = self.request.GET.getlist('symbol') I want it to return me data (just one latest object by date) per symbol example: if I passed in a list of symbols : ['MPSLTD', 'SANDESH'] I should get [ { "close": "591.00000", "symbol": "MPSLTD" }, { "close": "783.00000", "symbol": "SANDESH" } ] I tried to do distinct and earliest but was hitting a wall. EquityIntradayData.objects.using('marketdata').filter(symbol__in=symbol_list).distinct().earliest('date_time') How can I achieve this ? -
One table can not be foreign key to others except one table
For example class Room(models.Model): visitor = models.ForeignKey(Visitor) number = models.PositiveIntegerField() capacity = models.ForeignKey(Capacity, on_delete=models.PROTECT) floor = models.ForeignKey(Floor, on_delete=models.PROTECT) price = models.PositiveIntegerField() is_premium = models.BooleanField(default=False) is_vip = models.BooleanField(default=False) expiry_date = models.DateTimeField() class Meta: unique_together = ('') def __str__(self): return '№{0}'.format(self.number) class Reserved(models.Model): room = models.ForeignKey(Room) begin_date = models.DateTimeField() def __str__(self): return 'Reserved Room {0}'.format(self.room) class Busy(models.Model): room = models.ForeignKey(Room) Table Room can not be connected to Tables Reserved and Busy at the same time. Room should be reserved or busy. Is there way put validation for this? I tried to use unique_together but if for fields of table Thanks -
Django urls and 404 for every address
I got a new project to work on and I'm stuck. Whichever url I try to give I get 404 response from server and I can't figure out how urls are managed. In project urls root I have something like this: urlpatterns += patterns('', url(r'^$', include(resolver_urls, namespace='resolver')), url(r'^', include(other_urls, namespace='other')), url(r'^accounts/', include('accounts.urls', namespace='accounts')), ) This says AFAIK: "if nothing after slash is passed (for ^ is beginning of a stringand$matches end of it, nothing is expected between), then use urls from resolver_urls, otherwise search further". OK, but inresolver` I have this: urlpatterns = patterns( '', url(r'^.*$', ResolveUrlToRestaurantView.as_view(), name='resolver'), ) Which says "match any count of any character". If I try to connect to say 127.0.0.1:8080/signup which: is in other urls module: urlpatterns = [ (...) url(r'^signup/$', SignUpView.as_view(), name='signup'), (...) ] and is defined in views: class SignUpView(SignUpMixin, APIView): def post(self, request): self.signup_user(request) return Response(status=status.HTTP_200_OK) def get(self, request): return Response(status=status.HTTP_200_OK) and I have it in installed apps setting, I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8080/signup/ Raised by: other.views.api.SignUpView So 2 questions: does this url configuration make any sense? Why do I keep getting 404 for all requests? -
django use timedelta in template
I am new django. I have the following code to get the current time and my filter is to convert the string date to dateformat and convert it to solar calendar. Is there any way to find the date of tomorrow in the template and not in any python file? {% now 'Y-m-d' as value %} <script> var today = "{{ value|dateCustomFilter }}"; // var tomorrow = ? </script> -
How to return objects by popularity that was calculated with django-hitcount
I have itens in my app that I want to be returned by "popularity". This popularity meaning the number of views the item has. I'm using django-hitcount to do this. I saw here how I could get the number of hits of each object. But I don't want to load all my Item objects to memory to accomplish what I want because it's an unnecessary overload. I want to return the N most popular itens to be passed to the view and the access number of each item. My Item model is as bellow class Item(models.Model, HitCountMixin): nome = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, null=True) imagem = models.ImageField(upload_to='itens/item/', null=True, blank=True) descricao = RichTextUploadingField(null=True, blank=True) categoria = models.ForeignKey(Categoria) hit_count_generic = GenericRelation( HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') def __str__(self): return '{}'.format(self.nome) def get_absolute_url(self): from django.urls import reverse return reverse('itens:detail_item', args=[str(self.slug)]) At first, in my View I was trying to get the most popular itens with this function def get_most_popular_itens(amount): return Item.objects.order_by('-hit_count.hits')[:amount] But it didn't work. I couldn't understand how this contenttype/generic relationship works. So, I saw how the database tables were and managed to do something functional (see bellow). But it has one problem. The queryset returned isn't ordered by the number of views …