Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python - Skip weekend and public holiday when calculating duration between 2 datefield
Greeting everyone, I have 2 DateField in my form, start_date and end_date and a FloatField called duration. I figure out how to automatically save the duration without user input by calculating the duration of start and end date, but how can i give a condition to skip weekend, and any particular public holiday? Any help is much appreciated Below is my code : model.py : class Leave(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='+') start_date = models.DateField() end_date = models.DateField() duration = models.FloatField(null=True, blank=True) form.py : class LeavesDetailForm(forms.ModelForm): class Meta: model = Leave fields = ('employee', 'start_date', 'end_date', 'duration') widgets = {'start_date': forms.DateInput(attrs={'type': 'date'}), 'end_date': forms.DateInput(attrs={'type': 'date'}), 'employee': forms.HiddenInput(), 'duration': forms.HiddenInput()} view.py : def my_leaves_view(request): """ My Leaves view :param request: :return: """ form = LeavesDetailForm(request.POST or None) if form.is_valid(): inst = form.save(commit=False) inst.start_date = form.cleaned_data['start_date'] inst.end_date = form.cleaned_data['end_date'] duration = (inst.end_date - inst.start_date).days inst.duration = duration inst.save() return HttpResponseRedirect('/hrm/employee/leaves') return render(request, 'hrm/employee/details/my_leaves.html', context) -
Django Cookiecutter: How to import AUTH_USER_MODEL in config/settings/base.py?
As we know, Django-Cookiecutter has a different setup for settings files. The regular from django.conf import settings doesn't work here. I want to reference to the custom user model defined in the base.py file in the settings directory. Any ideas? -
Django inernal server Error
I'm working on Django website when I upload an image and its name in English language that will be upload but when I try to the Arabic language that can't upload, they give internal server error. -
CSV to Django models Date format in Django Models
In my models.py from_date = models.DateField(auto_now=False,auto_now_add=False) to_date = models.DateField(auto_now=False,auto_now_add=False) My csv has In my views.py Im inserting the data from csv reader = csv.DictReader(csvf) for row in reader: Csv.objects.create(from_date=row['from'],to_date=row['to']) Django is throwing me an error,"the date should be It must be in YYYY-MM-DD format." Is there any way to change the date format in django models directly with out Django Model Forms ? -
Jump to another page after press add buton django add form
i wan to jump to a page after i press a button which insert into a table with the help of a form {% extends "index.html" %} {% block title %} <title>Add banner</title> {% endblock %} {% block content %} <div class = "container"; align="center"> <h3 >Add banner</h3> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit"; onclick="location.href='/banner_list'"; value="Insert">Add</button> </form> <button style="height:50px;width:100px"; onclick="location.href='/banner_list';" type="button">Back</button> </div> {% endblock %} this is the template.I modifiy the template with button onclick and things like that but nothing works And this is the view : def add_form(request): form=BannerForm() last=models.banner.objects.last() if not last: id = 1 else: id = last.id if request.method == "POST": form = forms.BannerForm(request.POST, request.FILES or None) if form.is_valid(): form.cleaned_data['created_by'] new_banner=models.banner() new_banner.id=id+1 print new_banner.id new_banner.name=form.cleaned_data['name'] new_banner.company=form.cleaned_data['company'] new_banner.file=form.cleaned_data['file'] new_banner.file_name=new_banner.file.name new_banner.created_by=form.cleaned_data['created_by'] new_banner.save() return render(request, "add_banner.html",{"form":form}) -
Configuring NGINX for correct URL forwarding to Graphite docker image
I have a web application running on Debian through NGINX and UWSGI. We've begun using Graphite and statsd running in a docker container to collect stats on the application (from https://github.com/hopsoft/docker-graphite-statsd). The docker container has its own NGINX to serve Graphite. Currently we are running the docker container forwarding port 8081 to 80 and are able to access Graphite through http:// example.com:8081. I am trying to route the web traffic for Graphite through our existing NGINX server so that we will be able to use our established authentication method when accessing it. I would like to be able to access Graphite via example.com/graphite/ and have all associated content be referred to under that directory. Currently example.com/graphite/ forwards to http:// example.com:8091/graphite/. I would like for the url to not appear to change. From there, Graphite loads up, but all page elements load from :8091/, e.g. http:// example.com:8091/content/js/ext/resources/images/default/sizer/s-handle.gif, whereas I would like it to be referred to via http:// example.com/graphite/content/js/ext/resources/images/default/sizer/s-handle.gif. When I go to domain.com/graphite/admin/ I receive our web application's 404 page. The html for the admin page has loaded successfully, but I receive 404s for https:// example.com/browser/header/ and https:// example.com/composer/?. Here are the relevant sections of my current nginx.conf: # HTTPS … -
How to work with csv files on heroku
I am working on a small Django project in which I need to read data from a CSV file. everything is working fine on the localhost. But when I deploy it on Heroku, it says no CSV file found. Some code here def compi(df2): ratings_df=pd.read_csv('ratings.csv') ratings_df = ratings_df.append(df2, ignore_index=True) return ratings_df Am I missing something? Is there any other way to work with CSV or text files in Heroku -
How do you get the currently edited object or record inside formfield_for_manytomany in Django?
How do you access the currently edited object or record in the admin sites' formfield_for_manytomany function in Django? -
Error When Using Mechanize in Custom Module Imported to Django views.py file
I cannot for the life of me figure out what's going on here. I am making a site with Django that takes the username and password of someone logging in, runs it through a python script which uses mechanize to scrape another site, and then does some math and displays some data. The problem appears to be with mechanize when trying to run the file live with Django. Obviously, the scraping script works perfectly fine when run alone. Here is the traceback and all. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 1.11.4 Python Version: 2.7.12 Installed Applications: ['webapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback: File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/jackditto/Desktop/Django Site/mysite/webapp/views.py" in login 22. information = MySA_Scrape.get_grades(login, password) File "/usr/local/lib/python2.7/site-packages/django/modules/MySA_Scrape.py" in get_grades 90. login(username, password) File "/usr/local/lib/python2.7/site-packages/django/modules/MySA_Scrape.py" in login 31. response = mechanize.urlopen(request, data=encoded_params) File "/usr/local/lib/python2.7/site-packages/mechanize/_opener.py" in urlopen 433. return get_thread_local_opener().open(url, data, timeout) File "/usr/local/lib/python2.7/site-packages/mechanize/_opener.py" in get_thread_local_opener 426. ans = thread_local.opener Exception Type: AttributeError at / Exception Value: 'thread._local' object has no attribute 'opener' -
Django - AngularJS and JSON
I have been watching several tuitorials on Django and have come across the rest framework. So in this tuitorial I retrieved from the database and displayed it in my view as a json object. So if you go to my view, it just shows the database contents in json format. How can I get this data in a grid using angularJS within Django? My end goal is to have a grid where users can add or delete a row by the click of a button. -
Where does the **kwargs argument comes from the formfield_for_manytomany Django function? [duplicate]
This question already has an answer here: Understanding kwargs in Python 10 answers Where does the **kwargs argument comes from for the formfield_for_manytomany Django function? class MyModelAdmin(admin.ModelAdmin): def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "cars": kwargs["queryset"] = Car.objects.filter(owner=request.user) return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) kwargs["queryset"]? Does anybody know? -
Django complex model - matching events with where clause
In an existing database I have a table for tracking and correlating events and need some ideas on how to do this in Django. The intent is to query the table for sets of events that occur at the same time. (This is then used to do things like create a scatter-plot graph with one type of event on the x-axis and another type of event on the y-axis with each data point matched up by the time it occurred). The db schema looks like this. Table: Event EventTime, EventType, EventValue 2017-08-01 10:00, type1, 100 2017-08-01 11:00, type1, 200 2017-08-01 12:00, type1, 300 2017-08-01 10:00, type2, 10 2017-08-01 11:00, type2, 20 2017-08-01 12:00, type2, 30 2017-08-02 14:00, type3, 20 2017-08-02 16:00, type3, 30 A sample query might look like this (yes, it is MS-Access currently - it won't be after porting to Django): SELECT xaxis.EventTime as xEventTime, xaxis.EventType as xEventType, xaxis.Value as xValue, yaxis.EventType as yEventType, yaxis.Value as yValue, FROM Event as xaxis, Event as yaxis WHERE xaxis.EventTime = yaxis.EventTime and xaxis.EventType='type1' and yaxis.EventType='type2' and xaxis.Date_Hour_UTC > #2017-08-01 00:00# and xaxis.Date_Hour_UTC < #2017-08-02 00:00# With the result looking looking like this: xEventTime, xEventType, xValue, yEventType, yValue 2017-08-01 10:00, type1, 100, … -
sqlite3 database connection in Python Django project
I have problem in "python manage.py migrate" this command not working in Django Project on install install sqlite3 db ? -
Where should I lock a model to prevent race conditions while validating it on a Django admin change page?
The simplified case: models.py: class Candidate(Model): first_name = CharField(max_length=64) last_name = CharField(max_length=64) class Ward(Model): no = PositiveIntegerField(unique=True) address = CharField(max_length=1024) population = PositiveIntegerField() class Votes(Model): candidate = ForeignKey(Candidate, on_delete=CASCADE) ward = ForeignKey(Ward, on_delete=CASCADE) amount = PositiveIntegerField() In each Ward each Candidate may receive Votes.amount votes and the winner of the election is the Candidate who receives the most votes aggregated over Wards. These votes are editable in Django admin: admin.py: class VotesInline(StackedInline): model = Votes @register(Ward) class WardAdmin(ModelAdmin): inlines = (VotesInline,) Now validation issues kick in. Obviously the sum of the Votes.amount for all Candidates must not exceed a Ward's total Ward.population. However, such validation will be meaningless unless the Ward remains locked for the duration of the validation of all related Votes! Else a race condition may kick in if user A modifies Ward.population while user B modifies Votes.amount related to this Ward. I know that I should lock the Ward with select_for_update, but I do not know where exactly should I lock it so that the lock lasts for the validation of all related Votes. I was thinking about doing this in get_queryset, but ofc this would be a horrible idea, as this would lock it even while … -
How to Lengthen the Username Field on Django User Model?
I have a Django web application that is deployed on Heroku. I'm using Django's user model for authentication. My goal is to lengthen the username field from 30 characters to 100 characters. I overrode the default User model with my own AbstractUser model: class AbstractUser(AbstractBaseUser, PermissionsMixin): username = models.CharField( _('username'), max_length=30, unique=True, help_text=_('Required. 100 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[ 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(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), blank=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) I want to update the max_length of the username field from 30 to 100. I can do this locally without any issue by simply updating the line "max_length=30" to "max_length=100", running "python manage.py makemigrations" and "python manage.py migrate". However, the migration file is … -
Django admin template display
My django admin pages are displaying differently on local and on my hosting. The one on local is has better display. Both are running Django 1.11.4. What could have caused this? Image of Django admin with better display on local environment Image of Django admin with slightly different display on hosting -
How to redirect in django while using django-hosts?
I'm using django-hosts package to manage content that's supposed to be set in various different domains. I started by making a view in which a form is used to change something. Once the form is validated and processed, user is supposed to be redirected to some other page. Looking through documentation there's an easy way to render(): settings_url = reverse('settings', host='dashboard') return render(request, 'dashboard/settings.html', {'settings_url': settings_url}) However, there's no mention of redirect(). So how would I go about redirecting to somewhere else, instead of the usual return redirect("dashboard:settings") myapp/hosts.py : host_patterns = patterns('', host(r'www', settings.ROOT_URLCONF, name='www'), host(r'dashboard\.myapp\.com', 'dashboard.urls', name='dashboard'), ) dashboard/urls.py from .views import home, websitesettings urlpatterns = [ url(r'^$', home, name='home'), url(r'^settings/$', websitesettings, name='settings'), ] Basically all I want is to redirect back to the same page after form is submitted (in the render example, I'm submitting a form to change certain website settings, which is an app on it's own, and then I want to redirect back to the same page after that). -
Django all-auth app, how to modify /account/profile page to display custom view
After setting up the All-Auth app, when user logs in, he gets redirected to: accounts/profile/ page which tells us that the view doesn't exist. I'm trying to figure out what kind of thing to include there, and decided to allow the user to change their basic information. I have a users app with a Teacher model, which is set up as follows: class Teacher(models.Model): user = models.ForeignKey(User, unique=True) rate = models.CharField(max_length=200) availability = models.BooleanField(default=False) verified = models.BooleanField(default=False) I want the accounts/profile/ page to show a form, containing this information. The user can edit these fields and also edit their Firstname, Lastname and Email, which belong to a different Model - User. I can't seem to get started on this. When I created a detailed view for the profile page, I get an error saying: No PK or SLUG provided I want Django to change the current users info, not based on the primary key in the URL. Do I need a custom view? I've looked at [other solutions1 but they seem to be utilising the private key parameter. What I need is a working view function, something similar to (not working): def get_teacher_info(request): current_user = request.user teacher = get_object_or_404(Teacher, username=current_user.username) … -
Django - Object with many categories and many subcategories
I have been struggling with a model for this. Im developing a directory of companies in the music industry. We already have data base of 500 companies. We have this categories: Audio, Video, Ilumination, Stages, Music Intruments, Talent, Schools and Dj. This categories have this subcategories. - Audio: recording, installation, rent, retail - Video: installation, rent, retail - Ilumination: installation, rent, retail - Stages: Bars, Discos, theaters, stadiums - Music Intruments: retail, rent - Talent: manager, record label, booking - Schools: audio, production, theater, dance - Dj: booking, retail Many companies enter in many of this categories, and inside this categories they enter in many subcategories. Example: Company X sells video and audio products but the also offer the installation service for the audio products. So Company X - Audio: Retail, Installation. - Video: Retail In your opinion how can i manage to design the models???? Thanks in Advance. This is my code by far, but its wrong. -
Django: how to add a custom attribute to each element of queryset without N+1 request?
Suppose that I have a very basic user model with name and age: class User(models.Model): name = CharField() # e.g. John Smith age = IntegerField() # e.g. 21 I want to create a queryset of users, that filters only those older than 18 years old and create a special attribute that for each user contains a list of his namesakes (for instance, for "John Smith" it would be something like ["John Williams", "John for Neumann", ...]). I know, how to do this in N+1 requests: for user in User.objects.filter(age__gt=18): user.namesakes = User.objects.filter(name__startswith=user.name.split()).\ all() But how do I do this in one-ish request? Ideally, for each User object in queryset I'd like to create a custom attribute namesakes that contained a queryset of namesakes. This is very similar to what annotate() or prefetch_related() with to_attr do, but not exactly. I'd also prefer to avoid using raw SQL, if possible. Thank you. -
Querying through related models in Django
If I have: class App(models.Model): app_name = models.CharField(...) class Module(models.Model) module_name = models.CharField(...) class config(models.Model) config_date = models.DateTimeField() config_modules = ManyToManyField(Module) config_app = models.ForeignKey(Application) How do I get the apps that have a particular module? If m is a Module object. I know m.config_set.all() gives me all the configurations that have module m. And this: l = [] for conf in m.config_set.all(): l.append(conf.config_app.app_name) gives what I want, but is there a more terse syntax to achieve same? Thanks -
jQuery binds fail after the load function
I'm doing the AJAX requests with the library intercooler.js, but I tried with native AJAX and I got the same result. I submit the login form (which it is in a modal): <form id="loginForm" role="form" class="login-form" ic-post-to="{% url 'login' %}" ic-on-error="handleFormError(xhr,'loginForm');" ic-on-success="deleteAllErrors('loginForm');$('#loginModal').modal('hide');update('navbar');" data-toggle="validator">{% csrf_token %}...</form> When "ic-on-success" (success request) I refresh the div with id="navbar" (the header links). This function causes jQuery stop working: update('navbar'); function update(idDom){ $('#update-' + idDom).load(' #' + idDom); } Okey, now the div with id="navbar" (the header links) got refresh and the logout link appear, but this does not work anymore: <div id="update-navbar"> <div id="navbar" class="collapse navbar-collapse"> <a class="pointer" ic-get-from="{% url 'logout' %}" ic-on-success="update('navbar');"><i class="lnr lnr-exit"></i> Cerrar sesi&oacute;n</a> </div> </div> It's like jQuery stop working. I repeat, I tried with native AJAX and $("#target").click(function() {... too but the bind does not work. I have to refresh the whole page pressing F5 so that the logout link works again. -
Custom DRF list function not returning some of the dict key/value pairs
I'm trying to replace the standard list function inside a Django REST Framework viewset with a custom one, but am losing the count, previous, next params. With no override, a list function returns the following: { "count": 3, "next": null, "previous": null, "results": [...] } Whereas when I override the function, I only get the results list, not the higher-level dict with count, next, previous, etc. What part of the function below is missing from here that would enable that functionality? def list(self, request): loc = Location.objects.filter(user=request.user).latest('timestamp') nearby = loc.get_near() # returns a list with dicts that contain user and dist nearby_users = [n['user'] for n in nearby] # gets a list of users serializer = self.get_serializer(nearby_users, many=True) return Response(serializer.data) -
Get a queryset value in Django
How can I get the value of this queyset? I'm trying to get the value of name but it only show object. class Brand(models.Model): name = models.CharField(max_length=255, blank=False) class SubBrand(models.Model): name = models.CharField(max_length=255, blank=False) brand = models.ForeignKey(Brand) >>> print Brand.objects.filter(subbrand__id='2') <QuerySet [<Brand: Brand object>]> -
Django extending user with userprofile (error: User has no profile.)
someone can told me, why this code don't working? I'm trying to create a registration form for users. I'm getting an error "RelatedObjectDoesNotExist at /signup/client/2/ User has no profile." views.py if request.POST: user_form = UserCreationForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.profile.city="WW" user.profile.phone="32323" user.profile.save() forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'city', 'phone') html file <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <button type="submit">Sign up</button> models.py from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.TextField(max_length = 50) phone = models.TextField(max_length = 12)