Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Widgets in django smart-selects
Someone knows how to use widgets with smart-selects in Django? Is there any special widgets? The default forms.Select is not working correctly. -
Django: Best way to retrieve object
Lets assume that I have a class Person with a field email. I want to get a single record based on queryset and assign it to variable person. Sadly I cannot do person = Person.objects.filter(email="xxx@xxx.xxx")[0] because I might get an exception. So: Scenario 1: Include the above code in a try-except. Scenario 2 (which I'm currently using): person_arr = Person.objects.filter(email="xxx@xxx.xxx") if person_arr.exists(): person = person_arr[0] .... Scenario 3 for person in Person.objects.filter(email="xxx@xxx.xxx"): .... Scenario 4: You suggest something else. -
What should the page_name be in login.html?
I put the following in my user/templates/user/login.html: {% url 'social' page_name='what_should_this_say?' %} href="{% url 'social:begin' 'github' %}">Login with GitHub what should page_name be? http://github.something...? Thanks in advance. -
Django - Pass a model instance specified by template tags into view
On my HTML page, I have a list of Agent's (Agent is my custom User model). Beside each agent is a 'Send Invite' button. To create a TeamInvitation, I need to specify which Agent is attached to its receiver_agent field (a OneToOneField with Agent) There are multiple Agents displayed on the HTML page, and they are listed in order with template tags. I need to input something after pk at receiver_agent = Agent.objects.get(pk = ???), but I don't know what to input. views.py class InviteAgentSearchResults(ListView): model = Agent form_class = AgentSearchForm template_name = 'invite_agent_search_results.html' def get_queryset(self): # ... Code to find correct list of agents def post(self, request, *args, **kwargs): invite = TeamInvitation.objects.create(receiver_agent = Agent.objects.get(pk = ???)) return HttpResponse('Invite successfully sent.') HTML: {% for agent in agent_list %} <div class="agent"> # ... Some code here <form method="post"> # The "Send Invite" button {% csrf_token %} <button class="button1"><span>Send Invite</span></button> </form> </div> {% endfor %} -
Retrieving active user's username is not working in Django Rest Framework and Django
This is something that seems to painfully easy, but I can't get it working so have to ask. This is after reading the first few pages of Googling "django get username", or "django rest get username", and reading the several dozen SO answers on the subject. Simple enough: trying to get the name of the active user so I can retrieve records relevant to them. This is in my views.py where I am currently testing it and just trying to get it print(user) to console which isn't happening. # ./home/views.py from rest_framework.generics import ListAPIView from rest_framework.permissions import IsAuthenticated from django.contrib.auth.models import User from .serializers import GetHomeSerializer from .models import Home # Create your views here. class GetHomeAPIView(ListAPIView): queryset = Home.objects.all() serializer_class = GetHomeSerializer permission_classes = [IsAuthenticated] def get_username(self, request): user = request.user print(user) return user # ./home/serializers.py from django.utils.safestring import mark_safe from rest_framework.serializers import ( ModelSerializer, ) from .models import Home class GetHomeSerializer(ModelSerializer): class Meta: model = Home fields = '__all__' Everything is being returned to the React front-end as it should which is to render what is in the Home model, which is not user specific (basically a "welcome" message), but nothing indicating who the user is in console … -
Django Error Reporting ignore certain exception
When unhandled exception is raised, Django sends email with stacktrace. Is it possible to exclude certain exceptions from sending? For example, I don't want emails to be sent, when KeyError is raised. -
ajax post returns 404 for url in django 1.10
Im trying to post a simple ajax to 'signup' function in django but keep getting 404, I think it has to do with my url dispatcher and I need some help please.. my ajax looks like this: $('#signupBtn').click(function() { $.ajax({ type: 'POST', url : '/signup', dataType: "json", data : { userId : $('#signupEmail').val(), userPassword : $('#signupPassword').val() }, beforeSend: function() { $('#signupBtn').hide(); }, error: function(xhr,errmsg,err) { $('#signupBtn').show(); $('#signupEmail').val(""); $('#signupPassword').val(""); alert(xhr.status); }, success : function(json) { $('#signupBtn').show(); $('#signupEmail').val(""); $('#signupPassword').val(""); alert(json['u']); } }); return false;}); my views.py lookes like this: def signup(request): userid = request.POST.get('userId') userpass = request.POST.get('userPassword') data = { 'u' : userid, 'p' : userpass} return JsonResponse(data) and my app urls lookes like this: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^signup$', views.signup, name='signup'),] what is my problem? and how do i fix it? thanks. -
Django Python change user default attributes for authentication
In Django, the default attributes for user: username password email first_name last_name I would like to remove email, first_name, last_name and replace it with company Is that possible ? Can someone show me the process of performing an authentication session with these 3 modified attributes: - company - username - password Thanks. -
Incrementing a variable to use as serial number in django
I am currently using forloop.counter to display serial number but it skips the number when if condition is not satisfied. That is why I am not able to print the serial number. I need a way to increment a variable and then use it for serial number templates.html {% for all in all_lockscreens %} {% if all.media_type == "image" %} <tr> <td>{{ forloop.counter }}</td> <td>{{ all.media_name }}</td> <td>{{ all.description }}</td> <td>{{ all.date_added }}</td> </tr> {% endif %} {% endfor %} Need to increment a variable inside if loop which can be used for serial number -
Pycharm Django Supervisor Manage.py
I'm using Pycharm Professional edition to maintain a Django web application hosted on a remote Linux OS. Until now I've used Expandrive to mount the remote volume as a local windows mapped drive and can use remote debugging but would ideally like to develop locally and deploy to the server which I've got working but struggling to configure the run/debug configuration in conjunction with the Django settings in preferences considering I use supervisor to control all the processes. -
Using github to update website without re-deployment
I need to know how to update a website using github. Can't seem to find a clear example of that on the web. I have a djano project installed on my server. The app is in production. I basically need to know how I can connect it to my repository for my updates -
Installing mysql-python or mysqlclient for Django using pip throws error
I am starting to Learn python and Django framework. I already installed Django project and can run it. I am newboe to Python and Django. What I want to do is I want to connect to MySQL database of PhpMyadmin. I am using Xampp on windows for that. I followed this link - django, phpmyadmin and mysql?. But it throws error and saying I need to install python-mysql or mysqlclient. So I tried to install like this I also tried to install mysqlclient too. But both throwing following error. I searched solution and most of them say I need to update pip. I did it and my pip version is now latest and up-to-date. But it is still throwing that error when I install mysql-python and mysqlclient. Please how can I solve that error or how can I install in other way please? -
Django Admin Inlines for Indirectly Related ManyToMany Field
I have a few models as below and in the admin change form for Scenario I'd like to list, inline, all Users (i.e participants) that have "seen" that scenario through Simulation. models.py class Scenario(models.Model): name = models.CharField('Scenario', max_length=100) class Simulation(Event): scenario = fields.ForeignKey(Scenario, related_name='simulations') participants = fields.ManyToManyField(User, through='Participation') class Participation(models.Model): participant = fields.ForeignKey(get_user_model()) simulation = fields.ForeignKey(Simulation) How can I build or populate the ParticipationInline? What should the model be? admin.py class SimulationInline(admin.TabularInline): model = models.Simulation class ParticipationInline(admin.TabularInline): model = ...? class ScenarioAdmin(admin.ModelAdmin): inlines = (SimulationInline, ParticipationInline) I've tried a few things such as get_queryset and various 'dot' or 'dunderscore' joins... but I can't get it to work. The full queryset, if it can be done, would most likely have to be filtered as some Users would appear more than once. Thanks in advance for any help. Also if anyone can suggest a better way of phrasing the question/title... -
Simple log to console in Django 1.7.11
I've been breaking my head over creating a simple logfile within my django application. I've tried applying this question, as well as the examples on the docs, but it simply doesn't seem to work and I don't know what is going wrong. My current logfile, second example straight from the doc: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } The docs states the following: "this config only sends messages of level INFO or higher to the console" In my understanding, if I were to place this into my home.view.py file... import logging log = logging.getLogger(__name__) log.debug("Hey there it works!!") log.info("Hey there it works!!") log.warn("Hey there it works!!") log.error("Hey there it works!!") ...i should get the info, the warn and the error message printed to my console, whenever a call is made to home.views.py, which I thought happens when I visit the correct url. This appears to be false. It seems however that only warn and error is printed, and only when I run manage.py collectstatic. WARNING:home.views:Hey there it works!! ERROR:home.views:Hey there it works!! I want to receive the log messages in … -
Django ValueError - not enough values to unpack (expected 2, got 1)
Getting the error in the title when I try to go on my listing_public page, can't figure out why. views.py def listing_public(request, pk): listing = get_object_or_404(BuyerListing, pk) return render ( request, 'listing_public.html', context={'listing':listing} ) urls.py url(r'^listing/(?P<pk>\d+)/$', views.listing_public, name='listing_public'), Template Tags {% url 'listing_public' pk=listing.pk %} This is the only other question on Stack Overflow I found regarding this error, but the sole answer didn't solve my problem. Here is the traceback. -
Restricting admin urls to already authenticated superusers in Django
I've searched around for some solutions to this, but they all focus on a single admin url. However I was wondering if there is a way to restrict ALL the admin views, not the accounts to already authenticated superusers. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('accounts.urls')) ] What I want is urlpatterns = [ url(r'^admin/', is_superuser(admin.site.urls)), url(r'^accounts/', include('accounts.urls')) ] Or something like this that I can do in the view @user_passes_test(lambda u: u.is_superuser, login_url='allauth.account.views.LoginView') def superuser_only(request, template): return render(request, template) but still allows me to use admin.site.urls. Is there a quick and elegant way to solve this? I want all users including the superuser to authenticate through accounts app. -
Django 1.8 AttributeError("'module' object has no attribute 'commit_unless_managed'")
Seems like django 1.8 deprecated support for commit_unless_managed module. Any suggestions on what alternatives one should use ? -
Using Django Context Processors with forms
I have multiple forms to be shown everywhere in my project and hence I read that having a context_processor was the best way to do it. So, I created one inside my app and it looks something like this: def forms_processor(request): name_form = NewNameForm() work_form = NewWorkForm() address_form = NewAddressForm() context = {'name_form': name_form, 'work_form': work_form, 'address_form': work_form, } return context This works great, I can just use {{name_form}} anywhere in my templates and that renders the form. Now my question is, where do I validate the form? In my views.py or the context_processors.py? Right now my views for name_form looks something like this: def user_profile(request): if request.method == 'POST': name_form = NewNameForm(request.POST) if name_form.is_valid(): form.save() else: ctx = {'title': 'Profile', 'active_tab': 'Profile'} return render (request, 'user_profile.html', ctx) This isn't working actually, if I submit an invalid form, it just comes back to the same page and won't show a populated form. If someone could guide me or redirect me to some docs on this topic, that'd be awesome! Thanks! -
Authentication on Post DRF
I got an error on my DRF. when I try to authenticate using a post method. the token is the correct for the admin user. when I use a safe method it is sucessfull, but with the method post no, it doesn't authenticate my view class SpecialistListView(ListCreateAPIView): authentication_classes = (OAuth2Authentication,) permission_classes = (permissions.IsAdminUser,) queryset = Specialist.objects.all() serializer_class = SpecialistSerializer I don't understand why the status of the code returned is HTTP 401 Unauthorized. -
Avoid user pk in Django user edit form
I want to create a Django form to edit user information. I have: urls.py url(r'^settings/(?P<pk>[0-9]+)/', views.edit_profile, name='edit'), views.py @login_required def edit_profile(request, pk): user = get_object_or_404(User, pk=pk) if request.method == 'POST': form = UserForm(request.POST, instance=user) if form.is_valid(): form.save() else: form = UserForm(instance=user) return render(request, 'edit_user.html', {'form': form}) Like this, when a user edit its information can change pk from url and see other users information. How can I hide this pk in the url? Thanks. -
Multiple datetime fields for a model in Django
I want to create a log system to register some faults I need to handle at my work. I use Django and my models look like these: class Chan(models.Model): channelname = models.CharField(max_length=30) freq = models.FloatField(default = 0.0) def __unicode__(self): return u'%s' % (self.channelname) # timestamp object class EventTime(models.Model): since = models.DateTimeField() till = models.DateTimeField() def __unicode__(self): return u'%s' % self.since.strftime('%Y-%m-%d %H:%M') class Fault(models.Model): channel = models.ManyToManyField(Chan) description = models.CharField(max_length=200, default="-") message = models.TextField() timeevent = models.ManyToManyField(EventTime,null=True) visible = models.BooleanField() Firstly I used just one EventTime object but I soon realized I need to be able to choose several time periods because the same event could happen several times a day. So it would be too tedious to create a new record of Fault each time. So I basically needed something like this: The problem is that 'ManyToManyField' is too unhandy to use because I don't need to keep these values for other faults. So I don't know what solution I can use for it. I don't know how many time periods I need. Maybe I could add an extra Text field to my table where I would keep comma-separated datetime objects converted into a string like '2017-11-06 18:36,2017-11-06 18:37'. But … -
Create new model instance with one to one and foreign key field
Model: class BurrowedBook(models.Model): # Fields borrow_date = models.DateField() return_date = models.DateField() actual_return_date = models.DateField(null=True) # Relationship Fields book_copy = models.OneToOneField(BookCopy) burrowed_by = models.ForeignKey(Member) Save new instance: BurrowedBook.objects.create(borrow_date=borrow_date, return_date=return_date, book_copy=book_copy, burrowed_by=member) How do I save a new instance of this model? I'm having trouble with one to one field and foreign key field. -
Django - Add button to create foreign keys objects in modelforms
This is based on an old post Django: adding an "Add new" button for a ForeignKey in a ModelForm, it mentions ModelChoiceField. Is ModelChoiceField in Django 1.11? If not, what would you use instead? -
Static file error with Heroku and whitenoise - have run collect static
I redeployed an Django app to heroku, and am now getting static file issues: ValueError: Missing staticfiles manifest entry for 'css/styles.min.css' I had an error when upgrading boto (used for media files only not static files). So turned collect static off on heroku with: heroku config:set DEBUG_COLLECTSTATIC=1 After fixing the error I manually ran: heroku run python manage.py collectstatic --noinput to process the static files which produced no issues with the output: 239 static files copied to '/app/staticfiles', 263 post-processed However even though the collectstatic command worked I get the above the static files error above. I am using white noise on heroku with the production settings: `WHITENOISE_MIDDLEWARE = ('whitenoise.middleware.WhiteNoiseMiddleware', ) MIDDLEWARE = WHITENOISE_MIDDLEWARE + MIDDLEWARE WHITENOISE_MAX_AGE = 60 * 60 * 24 * 365 * 10 # 10 yrs STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'` and in requirements have whitenoise==3.3.1 I'm not clear what's causing the issue or how best to resolve as I've checked everything I can think of. -
PUT request being called more than once
I'm new to Ajax/jQuery and I am doing an assignment where I must use http method PUT to update a django model. The code I currently have works except for one issue: the PUT request is being run multiple+1 times each time I click on a new modify button and submit the form. Example via console.log: (index):121 BUTTON: Pressed modify on product ID: 87 (index):133 GET: Looped through products for ID 87 and set the values in the modal accordingly (index):153 PUT: Received put request for ID: 87 (index):121 BUTTON: Pressed modify on product ID: 88 (index):133 GET: Looped through products for ID 88 and set the values in the modal accordingly (index):153 PUT: Received put request for ID: 87 (index):153 PUT: Received put request for ID: 88 (index):121 BUTTON: Pressed modify on product ID: 89 (index):133 GET: Looped through products for ID 89 and set the values in the modal accordingly (index):153 PUT: Received put request for ID: 87 (index):153 PUT: Received put request for ID: 88 (index):153 PUT: Received put request for ID: 89 Code for ajax: // MODIFYING A PRODUCT product_ul.on("click", ".modify", function () { // On clicking modify var id = $(this).parents('li').attr('id'); // Get the PK …