Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: dynamic URL for user profiles
So I'm trying to make a pretty conventional dynamic URL profile pages for my users. So eg. www.website.com/profile/(username) I am getting an error of NoReverseMatch when I enter a valid username, and I do not know why. Here are snippets of my code urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^signup/$', accountsViews.signup, name="signup"), url(r'^logout/$', authViews.LogoutView.as_view(), name='logout'), url(r'^login/$', authViews.LoginView.as_view(template_name='login.html'), name="login"), url(r'^find/$', findViews.find, name="find"), # url(r'^profile/$', accountsViews.profile, name="profile"), url(r'profile/(?P<username>.+)/$', accountsViews.profile, name="profile"), url(r'^$', views.home, name="home"),] views.py def profile(request, username=None): if User.objects.get(username=username): user = User.objects.get(username=username) return render(request, "profile.html", { "user": user, }) else: return render("User not found") html file {% if user.is_authenticated %} {% url 'profile' as profile_url %} <li {% if request.get_full_path == profile_url %}class="active"{% endif %}><a href="{% url 'profile' %}"><span class="glyphicon glyphicon-user"></span> Profile </a></li> <li><a href="{% url 'logout' %}"><span class="glyphicon glyphicon-log-out"></span> Log Out</a></li> {% endif %} Also it if it helps, the error message is highlighting the "{% url 'profile' %}" part as the error, and claiming that it does not have a reverse match. However, in my urls.py, you can clearly see that I have done name="profile" Any help would be greatly appreciated. Thank you! -
Create customized DateTimeField
I am trying to implement a restaurants website to practice using Django. In models.py, I have a class called RestaurantLocation,with the following lines: class RestaurantLocation(models.Model): updated = models.DateTimeField(auto_now=True) I attempt to add a field visited to represent the first time I visited it. To accomplish it,I look through 'DateTimeField' DateField in django documentation. There are only two methonds of auto_now_add and auto_now without options to setup my own datetime. How to customize DateTimeField for my own datetime? -
How can I distinguish a user is AminUser or normal User in the custom User model?
I want to create a custom User by inherit the AbstractUser: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substituting-a-custom-user-model But, there is a issue for me, when I use the permissions, there is a IsAdminUser permission. If I have two custom User models, such as User model, and AminUser model (all of them inherit form AbstractUser). How can I distinguish a user is AminUser or normal User in the custom User model? -
When develop a Django project, how to design the User model?
In Django project, there is a default User model, because in the database, there is auth_user table: So, when I create a the User model in models.py, whether I should inherit the django's User or inherit models.Model? Because I should use the permissions in my project. EDIT and, what's the Django's User model? if is the django.contrib.auth.models.AbstractUser? -
Django rest framework json web token logout function
First of all, i am still new to django rest framework jwt so pls excuse my stupidity if im wrong. Im wondering about how to create a logout function for jwt as when user want to logout and switch account, they will need this function. Based on the what i seen in many other logout post, - there is no need for logout function as the token isnt save on server side so closing and opening will result in having to login again. - jwt is using expire time for it so it will logout when the token has been expire , provided if the verify token is set to True But what i want is to have like a remember me function where user will stay login when they close and open again, as one of the suggestion is turn the verify token to false or set expire time to weeks. But then how does the user logout if the token expire time hasnt reach yet ? As i am using jwt and djoser, the logout function of djoser is for drf only and not for jwt. Since i am also using the api for mobile devices, so the … -
How to replace url paramater dynamically in html page with django?
Basically, I have a template which have a search form and a table to show the result. The result can be ordered if header column is clicked. I use get method in search form and sort the result's table by getting the last url. views.py if sort_by == "desc": order_by = order_by sort_by = "asc" else: sort_by = "desc" url = request.META.get('HTTP_REFERER') if (url != None): search_params = {} param = urlparse.urlparse(url) if (not 'search_button' in request.GET): get_request = re.split('&',param.query) for single_request in get_request: search_query = re.split('=',single_request) search_params[search_query[0]] = search_query[1] userlist = show_data(order_by,sort_by,search_params) else: userlist = show_data(order_by, sort_by, request.GET) def show_data(order_by, sort_by, get_data): //the function get the value from db return row template.py <table id="user-table"> <tr> <th><a href="?order_by=userId&sort={{sort}}">User id</a></th> <th><a href="?order_by=userName&sort={{sort}}">Name</a></th> <th><a href="order_by=userAddr&sort={{sort}}">Address</a></th> </tr> <tbody> {% for item in table_data %} <tr> <td>{{ item.userId|default_if_none:"" }}</td> <td>{{ item.userName|default_if_none:"" }}</td> <td>{{ item.userAddr|default_if_none:"" }}</td> </tr> The search form able to filter and table result can sort the data. Here is the sample url if the search button is clicked http://localhost:8080/userlist/?&userId=&userName=Jane&userAddr=&search_button=search url if the column header is clicked http://localhost:8080/userlist/?order_by=userAddr&sort=asc However, it cannot do sorting again since the the url changed and search_param did not get the userName=Jane Is it possible to replace url parameter … -
ImportError: No module named 'accounts' - Heroku
When trying to deploy to Heroku, I am receiving the following error: 22:06:03 web.1 | apps.populate(settings.INSTALLED_APPS) 22:06:03 web.1 | File "/Users/XXX/.envs/carla/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate 22:06:03 web.1 | app_config = AppConfig.create(entry) 22:06:03 web.1 | File "/Users/XXX/.envs/carla/lib/python3.5/site-packages/django/apps/config.py", line 94, in create 22:06:03 web.1 | module = import_module(entry) 22:06:03 web.1 | File "/Users/XXX/.envs/carla/lib/python3.5/importlib/__init__.py", line 126, in import_module 22:06:03 web.1 | return _bootstrap._gcd_import(name[level:], package, level) 22:06:03 web.1 | ImportError: No module named 'accounts' Installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_summernote', 'widget_tweaks', 'accounts', ... ] Project structure: - carla/ - carla/ - accounts/ - static/ - templates/ - config - settings/ - __init__.py - urls.py - wsgi.py - manage.py - Procfile - requirements.txt ... Would anyone know why Heroku isn't able to find my 'accounts' app? It works fine locally, and is obviously in my INSTALLED_APPS. Thank you in advance! -
Create an list/dictionary of form fields in Django
I want to create a list of unique radio select options for a game in Django that exponentially increases with each round. So in round 1, the player has 1 radio button to select from. Round 2, the player has 2 radio buttons to select from. Round 3, the player has 4 radio buttons to select from. Crucially, each of these forms needs to have a unique identifier so that the player can select all options for a particular round. For example, for round 3, my form contains the following code: <tr> <td class="tb" rowspan="2"><p {% formfield player.r3_decision1 with label="" %}</p></td> </tr> <tr> <td class="tb" rowspan="2"><p {% formfield player.r3_decision2 with label="" %}</p></td> </tr> <tr> <td class="tb" rowspan="2"><p {% formfield player.r3_decision3 with label="" %}</p></td> </tr> <tr> <td class="tb" rowspan="2"><p {% formfield player.r3_decision4 with label="" %}</p></td> </tr> Player is then declared as a class in models.py, with player containing each of the form fields defined above as attributes. class Player(): r3_decision1 = models.CharField( choices=['A Option A','B Option B'], widget=widgets.RadioSelectHorizontal(), blank=False, initial='blank' ) r3_decision2 = models.CharField( choices=['A Option A','B Option B'], widget=widgets.RadioSelectHorizontal(), blank=False, initial='blank' ) r3_decision3 = models.CharField( choices=['A Option A','B Option B'], widget=widgets.RadioSelectHorizontal(), blank=False, initial='blank' ) r3_decision4 = models.CharField( choices=['A Option A','B … -
how can i fix this error ; resolver error in tests.py
enter image description here i got this error when run python manage.py test def test_update_status_using_index_func(self): found = resolve('/update-status/') self.assertEqual(found.func, index) -
how to redirect "print" command output to a file without changing the python code?
I want to redirect all the output of my django app to a file Firstly, I tried: python manage.py runserver 0.0.0.0:8000 >test.log 2>&1 But it doesn't redirect the output of print command. For example, in my code there is a statement: print ('query_content:') using command: python manage.py runserver 0.0.0.0:8000 I can see that 'query_content:' is printed out in the screen. But with : python manage.py runserver 0.0.0.0:8000 >test.log 2>&1 In the test.log, there are only something like this: [05/Nov/2017 20:38:20] "GET ... HTTP/1.1" 200 22404 [05/Nov/2017 20:38:26] "POST ... HTTP/1.1" 200 13 [05/Nov/2017 20:38:26] "GET .... HTTP/1.1" 200 16800 [05/Nov/2017 20:38:30] "GET ... 200 22430 ... One solution is: import sys sys.stdout = open('file', 'w') print 'test' But sometimes it is impossible to change the python code, is there any solution? -
Images not showing up with template tags in Django templates
I'm trying to display a user-uploaded image on my HTML template. I tried a bunch of template tags but none of them seem to be working. All the settings appear to be configured correctly. User-uploaded images are correctly uploaded to project_name/media/ settings.py MEDIA_URL = '/media/' MEDIA_ROOT = 'project_name' # Are the STATIC settings affecting the media settings? media is for user uploads so I don't think so? STATICFILES_DIRS = [ 'project_name/static/', ] STATIC_URL = '/static/' Things I tried in this HTML: # 'app.profileapp' is not the issue here. I can access other 'profileapp' attributes just fine (e.g. 'app.profileapp.agent_website' shows up just fine) <img src = "{{ app.profileapp.agent_picture }}" alt='My image' /> <img src = "{{MEDIA_URL}}{{ app.profileapp.agent_picture }}" alt='My image' /> <img src = "{{MEDIA_ROOT}}{{ app.profileapp.agent_picture }}" alt='My image' /> <img src = "{{ app.profileapp.agent_picture.url }}" alt='My image' /> <img src = "project_folder/{{ agent.agentpremiuminfo.agent_picture }}" alt='My image' /> <img src = "project_folder/media/{{ agent.agentpremiuminfo.agent_picture }}" alt='My image' /> -
Django DateTimeField Chunking, Averaging, and Reformatting
Here is the model I'm working with: class BTCPrice_kraken(models.Model): """ Defines BTC Price Model - Kraken """ id = models.AutoField(primary_key = True) date_time = models.DateTimeField(auto_now = True) code = models.CharField(max_length = 3) last_trade = models.FloatField() last_trade_volume = models.FloatField() ask = models.FloatField() ask_lot = models.FloatField() ask_whole = models.FloatField() bid = models.FloatField() bid_lot = models.FloatField() bid_whole = models.FloatField() open = models.FloatField() high = models.FloatField() high_24 = models.FloatField() low = models.FloatField() low_24 = models.FloatField() volume = models.FloatField() volume_24 = models.FloatField() I need a way to pull ranges from date_time, store all the keys in that range, average the data from keys in the range, and reformat the date_time response to look better than it does raw. For example: I want a 15 minute chunk of time from the DB (the objects are added in 1 minute increments). I want to average all the objects in this chunk and return the averages by column label. And list them by (%d, %m, %y, %h%h, %m%m). How would I go about building query's (preferably with list comprehension and django's built in db modelling) to do this? I'm using Postgres DB and stock Django. -
is there pywebview Alternatives that depend on chrome and not on safari
Is there's any similar or alternatives to Pywebview: https://github.com/r0x0r/pywebview While it depends on the version of installed Safari on OS X and QT. I am trying to make a desktop app out of Django project. but a lot of features (css & javascript) are not working well on Safari neither Pywebview, and works perfectly on chrome. After that it will be all encapsulated with py2app. Ps: Or, is there a way to make it depend on chrome. -
Django query - link 2 tables over 3rd
I have tables Company, City and linking table CompanyCity (this is just an example). class Company(Model): name = CharField() class City(Model): name = CharField() country = CharField() class CompanyCity(Model): company_id = ForeignKey(Company) city_id = ForeignKey(City) Can you please help to write an optimal query to get a list a companies with a distinct list of countries which their offices are placed in. For example we have such data: IBM - Washington, USA; Vancouver, Canada; Stockholm, Sweden; Microsoft - Washington, USA; Denver, USA; New York, USA; Toronto, Canada; I need to get: IBM - USA, Canada, Sweden Microsoft - USA, Canada -
django-admin: How to redirect to URL after one Object save?
I am using Django Signals to Trigger Code once the user is created i am saving additional data on another model class, it's getting triggered but it's not redirecting to additional data object page. Here is my models.py from django.db import models from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save class Customers(models.Model): user = models.OneToOneField(User) business_name = models.CharField(max_length=250) address = models.CharField(max_length=500) area = models.CharField(max_length=250) city = models.CharField(max_length=250) state = models.CharField(max_length=250) pincode = models.IntegerField(default='0') phone = models.IntegerField(default='0') mobile = models.IntegerField(default='0') def create_customer(sender, **kwargs): if kwargs['created']: customer_profile = Customers.objects.create(user=kwargs['instance']) post_save.connect(create_customer, sender=User) and here is my admin.py from django.contrib import admin from .models import Customers from django.shortcuts import redirect admin.site.register(Customers) class Customers(admin.ModelAdmin): def response_add(self, request, obj, post_url_continue=None): return redirect('/admin/app/customers/add/') def response_change(request, obj): return redirect('/admin/app/customers/add/') Tired looking for the answer but nothing works, please correct me here. -
'bundle' reserved word in django??`
I have a project I am working on and I create a table called bundle. I also have a foreignkey in another table that references the bundle table. When i try to access the foreignkey, it tells me that bundle is a keyword that is reserved. I also tried checklist and get the same error. I looked online and it didnt show that bundle or checklist is a reserved or keyword. can anyone help me with this. Here is the code that I have and is giving me the error. It is the second of the two lines. Thank you. bundles = Bundle.objects.filter(group = currentGroup).all() items = Items.objects.filter(bundle.group = currentGroup).all() File "/Users/omarjandali/Desktop/yap/opentab/tab/views.py", line 695 items = Items.objects.filter(bundle.group = currentGroup).all() ^ -
How to integrate Google API Client library with Django Rest Framework
I'd like to implement authentication between the Android client and Django Rest Framework server. I finally settled on this method. Now I would like to know how to integrate Google's API Client Library with Django Rest Framework. Specifically, how do I create the requests.Request() object in Django Rest Framework? -
Python/Django: How to handle simple search in advanced search engine?
I am working on advance search engine that allow multiple-layered of search(advance search) but I am not sure on how to carry simple search with the search form that contain multiple search fields. E.g: In the form I got a textbox, a dropdownlist that contain several types of fruits and a submit button. The problem is when I decide just to carry a simple search by just simply enter some string into the textbox without choosing the types of fruit and leaving it as the default value " ", when I submitting the form it generated URL: "http://127.0.0.1:8000/result/?q=something&fruit_type=+". Is there a way to remove the "&fruit_type=+" from the URL? <form action="/result/" method="get"> <input type="text" id="search_box" name="q"/> <input type="submit" id="sbm_button" value="SEARCH" class="inputbtn"/> <br /> <select name="Fruits"> <option value=" ">Fruits</option> <option value="apple">Apple</option> <option value="orange">Orange</option> </select> </form> Below is the view.py file: def search(request): if 'q' in request.GET: q = request.GET['q'] fruit_type = request.GET['Fruits'] return render(request, 'result.html', { 'query' : q, 'fruit' : fruit_type, }) It will return the q and fruit_type to result.html with the generated URL which had mentioned above. Is there a way to ignore the Fruits dropdownlist within the form(submitting the form and ignoring the dropdownlist)? Thank you. -
How to setup simple token based authentication in Android?
I want to setup a token based authentication in Android. The way I want/imagine this to work is like this: The Android client makes a POST request to the server together with the token, client_id, client_secret which it retrieved from the Account Manager.. The server reads the token, finds the user associated with the token and processes the POST request. If the POST request arrived without a token in step 2, the server creates the User, a token for the User and sends that token to the client which stores it in the AccountManager for future use. The server will ofcourse, before returning the token to the client, also process the POST request as in step 2. Is that a common technique? That's what I understood this Django Rest Framework article describes. Let me know please if this is the way to go. Otherwise, what do I do? I prefer not to use passwords at all. Why use passwords if the user has a phone with a Google Account? -
Saving entity with many to many self field throws exception
I am trying to provide an Admin interface for Category tree. My Categories are able to have several parents. I use many-to-many self field in order to provide that. Also I have some categories which were created using sql. models.py class Category(models.Model): id = models.AutoField(primary_key=True) active = models.BooleanField() description = models.CharField(max_length=255, blank=True, null=True) title = models.CharField(max_length=255, blank=True, null=False) url = models.CharField(max_length=255, blank=True, null=True) parents = models.ManyToManyField('self', through='CategoryParents', symmetrical=False, blank=True) def save(self, *args, **kwargs): if self.id is None: self.id = Category.objects.latest('id').id + 1 super(Category, self).save(*args, **kwargs) def __str__(self): if self.description is not None: return self.title + ": " + self.description else: return self.title class Meta: managed = False db_table = 'category' verbose_name = 'Category' verbose_name_plural = 'Categories' class CategoryParents(models.Model): category = models.ForeignKey(Category, related_name='category_id') parent = models.ForeignKey(Category, related_name='parent_id') class Meta: auto_created = True managed = False db_table = 'category_parents' unique_together = (('category', 'parent'),) def __str__(self): if self.parent.id is 1: return self.category.title else: return self.parent.title + "->" + self.category.title admin.py class CategoryForm(forms.ModelForm): parents = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Parents', is_stacked=False, ) ) class Meta: model = Category fields = ('title', 'id', 'description', 'url', 'active') def __init__(self, *args, **kwargs): super(CategoryForm, self).__init__(*args, **kwargs) # if self.instance: # self.fields['parents'].initial = self.instance.parents.all() def save(self, commit=True): category = … -
Mathjax does't work in django when linebreaks filter is used in django-template,but renders successfully without this filter
Mathjax does't work in django when linebreaks filter is used in template that is $$ {{text|linebreaks}} $$ doen't work but $$ {{text}} $$ renders successfully . But the problem is it's not responsive hence linebreaks filter is needed. Is there anyway that mathjax can render and be responsive (changes with screen-size) -
Where should I start to make a django website that finds recipes using ingredients, any book or tutorial recommendation ? [on hold]
I am a beginner in python and would like to make a website where you can search the recipes using ingredients. I am a frontend developer. Any recommendations where I should start ? -
Django - update child form as table on parent template
I have a Customer model and each customer has specific products that they buy which stored in the Template model. I have a customer detail view that displays the TemplateForm as a table. I'm trying to edit the existing instances in this table. Because there are multiple products for each customer I'm getting a MultipleObjectsReturned error when trying to load the url. When I remove the instance argument from my form I can see all of the proper template data. Not sure where to go from here. models.py class Customer(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(max_length=150, null=True, blank=True) class Template(models.Model): customer = models.ForeignKey(Customer) product = models.ForeignKey(Product) views.py def browse(request, slug): template_name = 'customer_browse.html' customer = get_object_or_404(Customer, slug=slug) products = Template.objects.get(customer=customer) if request.method == 'POST': form = TemplateForm(request.POST or None, instance=products) if form.is_valid(): return redirect('customers') else: form = TemplateForm(instance=products) return render(request, template_name, {'customer': customer, 'form': form}) html <form method="post"> {% csrf token %} <table> <thead> ... </thead> <tbody> {% for template in customer.template_set.all %} ... </tbody> </table> -
Python/Django =- ModuleNotFoundError: No module named 'restaurants'
traceback (most recent call last): File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Users\Archibald\Dev\trydjango1-11\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 978, in _gcd_import File "", line 961, in _find_and_load File "", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'restaurants' -
Django: function not being executed randomly but only sometimes
Working on developing an online game that is based around a user clicking a button and the game timer resetting to 10 seconds if it is already under 10 seconds (like auction sites), setting that user's username as the top user for the game, and using 1 of that user's tokens. The button works almost all of the time, but occasionally when a user clicks the button, a token of theirs will be used, but the timer will not reset to 10 seconds if it is already under 10 AND the top user for the game will not be updated to display their username. Here is the function that handles the button click on the game page. If the user does not have any tokens it will redirect them to the store page. If the user is already the top user or the game is over (game_object.status = 0) then they will simply be redirected back to the same page without a token being played or the game being updated: def game_page(request, game_id): game_object = Game.objects.filter(id=game_id)[0] context = {'game_object': game_object} if request.GET.get(str(game_object.pk)) and request.user.profile.get_tokens() > 0: if game_object.get_top_user() != request.user.username and game_object.status == 1: request.user.profile.use_token() game_object.update_game(request.user.profile.user) # fail safe if …