Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating model object in class based view with url pk
I am trying to create an object (without a form) with a primary key that is in my url. However self is not defined. I've tried using get_context_data and get_queryset, but I cannot figure out how to obtain the pk from my url. Model: class SalonOwner(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) class Meta: verbose_name_plural = "Salon Owners" def get_absolute_url(self): return reverse('accounts:salon-signup', kwargs={'pk': self.pk}) def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) View: class CreateOwner(View): owner_obj = models.SalonOwner(user_id=self.kwargs['pk']) owner_obj.save() def get_success_url(self): url = self.object.get_absolute_url() return url Url: url(r"create-owner/(?P<pk>\d+)/$", views.CreateOwner.as_view(), name="create-owner"), -
Trouble installing mysqlclient via pip
I'm working on a Django (1.9.2) project where I need to connect to a MySQl database, and I'm trying to use the recommended mysqlclient library. However, when I attempt installation via pip install mysqlclient I get the following error: Complete output from command python setup.py egg_info: sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/v9/vxdt4wms0_qgm9n10rt74p8m0000gn/T/pip-build-Xh__3p/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found Where do I need to create this missing mysql_config? -
Get all related datas from 4 tables
I have 4 related tables need send all filered data in AJAX response i use .all() but i get only 1 related table data. Can u help me? How i can get all related datas from 4 tables ShopMenu.objects.filter(shop=shop_id).all() "[ {"model": "catalog.shopmenu", "pk": 66, "fields": {"name": "\u0417\u0430\u0432\u0442\u0440\u0430\u043a\u0438", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 67, "fields": {"name": "\u0421\u0430\u043b\u0430\u0442\u044b \u0438 \u0437\u0430\u043a\u0443\u0441\u043a\u0438", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 68, "fields": {"name": "\u0421\u0443\u043f\u044b", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 69, "fields": {"name": "\u0413\u043e\u0440\u044f\u0447\u0438\u0435 \u0431\u043b\u044e\u0434\u0430", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 70, "fields": {"name": "\u041d\u0430\u043f\u0438\u0442\u043a\u0438", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 71, "fields": {"name": "\u0424\u0438\u0442\u043d\u0435\u0441 \u043c\u0435\u043d\u044e", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 72, "fields": {"name": "\u041c\u0430\u043a\u0430\u0440\u043e\u043d", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 73, "fields": {"name": "\u041a\u043e\u043d\u0444\u0435\u0442\u044b", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 74, "fields": {"name": "\u0414\u0436\u0435\u043c\u044b", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 75, "fields": {"name": "\u041c\u043e\u0440\u043e\u0436\u0435\u043d\u043e\u0435 \u0438 \u0441\u043e\u0440\u0431\u0435", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 76, "fields": {"name": "\u041b\u0438\u043a\u0435\u0440\u044b", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 77, "fields": {"name": "\u0421\u043b\u0430\u0434\u043e\u0441\u0442\u0438", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 78, "fields": {"name": "\u0412\u044b\u043f\u0435\u0447\u043a\u0430", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 79, "fields": {"name": "\u041f\u0438\u0440\u043e\u0436\u043a\u0438", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 80, "fields": {"name": "\u041f\u0438\u0440\u043e\u0433\u0438", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 81, "fields": {"name": "\u041f\u0438\u0440\u043e\u0436\u043d\u044b\u0435", "shop": 4}}, {"model": "catalog.shopmenu", "pk": 82, "fields": {"name": "\u0410\u043d\u0442\u0440\u0435\u043c\u0435", "shop": 4}}, {"model": … -
create or update device group(one-to-many) in django-rest-framework
There is a relation of one-to-many between Device and Device Group. A device can be on only one group(same device cannot be on multiple group) and a group can have multiple devices. I have designed the model according to the relation. But how can i create and update the device group where device io is also there as a foreign key? models class Device(BaseDevice): """ This stores Device """ description = models.TextField(blank=True, null=True) device_group = models.ForeignKey('DeviceGroup', null=True, blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_on= models.DateTimeField(auto_now=True) class DeviceGroup(models.Model): name = models.CharField(max_length=250, blank=False, null=False) created_on = models.DateTimeField(auto_now_add=True) updated_on= models.DateTimeField(auto_now=True) class IO(models.Model): name = models.CharField(max_length=250, blank=False, null=False) device = models.ForeignKey(Device, related_name='io') serializers class DeviceGroupSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() class Meta: model = DeviceGroup fields = ('name',) class DeviceSerializer(serializers.ModelSerializer): # Only token, secret_key and is_product are readonly id = serializers.UUIDField(source='token', format='hex', read_only=True) ios = IOSerializer(read_only=False, many=True, required=False) device_group = DeviceGroupSerializer() class Meta: model = Device fields = ('id', 'name', 'description', 'ios','device_group') def save_ios(self, device, ios): for io in ios: token = io.pop('token', None) if token is None: IO.objects.create(device=device, **io) else: IO.objects.filter(token=token, device=device).update(**io) def update(self, instance, validated_data): ios = validated_data.pop('ios',[]) instance = super(DeviceSerializer, self).update(instance, validated_data) if len(ios): self.save_ios(instance, ios) return instance def create(self, validated_data): ios = validated_data.pop('ios',[]) instance … -
How to make next and previous post button on my blog in Django?
I am making next and previous post button work on my blog in Django/Python. I thought it would be possible if I give a next or previous ID of articles to my URL like http://localhost:8000/3/. So I did as follows next_article = Article.objects.filter(id__gt=article.id).order_by('id').first() previous_article = Article.objects.filter(id__lt=article.id).order_by('id').first() <li><a href=" {{ previous_article }} ">Previous</a></li> <li><a href=" {{ next_article }} ">Next</a></li> their return values are definitely just the numbers when I print them in my console. but it doesnt work on my real blog. Their values are just the same as their original ID of the present post. How do I make this right? -
Tmpfile error with django-import-export on Heroku
I am using django-import-export to process CSV files uploaded to my Django admin site. When I run Django on my local machine, all works fine. When I deploy my application to Heroku I start getting errors related to tmpfile access: Feb 24 14:35:12 test-staging app/web.3: ERROR 2017-02-24 22:35:12,143 base 14 139687073408832 Internal Server Error: .... Feb 24 14:35:12 test-staging app/web.3: File "/app/.heroku/python/lib/python2.7/site-packages/import_export/admin.py", line 163, in process_import Feb 24 14:35:12 test-staging app/web.3: data = tmp_storage.read(input_format.get_read_mode()) Feb 24 14:35:12 test-staging app/web.3: File "/app/.heroku/python/lib/python2.7/site-packages/import_export/tmp_storages.py", line 42, in read Feb 24 14:35:12 test-staging app/web.3: with self.open(mode=mode) as file: Feb 24 14:35:12 test-staging app/web.3: File "/app/.heroku/python/lib/python2.7/site-packages/import_export/tmp_storages.py", line 31, in open Feb 24 14:35:12 test-staging app/web.3: return open(self.get_full_path(), mode) Feb 24 14:35:12 test-staging app/web.3: IOError: [Errno 2] No such file or directory: u'/tmp/tmpvCUtrP' I've read up on what I can about Heroku ephemeral storage, it seems like this should work. I've verified I can create, view, and modify files in /tmp on a heroku dyno with my code via heroku run. django-import-export has a module that allows you to overload the tempfile creation mechanism - but I'm not even sure what's wrong here (or, rather, why /tmp/tmpvCUtrP isn't getting created or isn't visible). -
Django middleware and never-ending loop
I need this snippet to do 2 things when user access / page: Store GET params into session variable for later use. If there are any params loaded in session use them to construct url, otherwise redirect to url with today as params as service_date_0 and service_date_1 My code from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import redirect from datetime import datetime class ParametrizeMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if request.path == '/': request.session['parametrized_url'] = request.get_full_path() if request.session['parametrized_url'] == '/': today = datetime.now().strftime('%m/%d/%Y') url = '/?service_date_0={}&service_date_1={}&qf=today'.format(today, today) return redirect(url) else: return redirect(request.session.get('parametrized_url')) response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response Long version I want to add to my application ability for users to go back to filtered results they were looking on homepage. Right now, when user navigates away from homepage, GET params get lost. I want them to be saved and display latest params used on homepage. And if there are no params set, use default params. Problem My … -
How to manage static files from Django 1.8 to Django 1.10
I have troubles with upgrading my project from Django 1.8 to Django 1.10: static files are not loaded anymore. My template looks like this: {% load staticfiles %} <!DOCTYPE html> ... <link href="{%static 'file.css' %}" rel="stylesheet"> ... Then in my file settings.py, I have 'django.contrib.staticfiles' as an installed app. DEBUG is set to True, and I have: STATIC_URL = os.path.join(BASE_DIR, 'static/') STATIC_ROOT= os.path.join(BASE_DIR,'static/') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/'), "./", ] But when the html is produced, it is like the %static has no effect anymore. It is replaced by the empty string (the same works fine with Django 1.8, where the %static is replaced by the content of STATIC_URL). Does anyone know how to fix this ? -
django Create view show error not working
how i can prevent the Repetition of renting a car for the same period the car was already rented or reserved for ex : 01/01/2017 to 01/03/2017 if i trie to rent this car for a period between this dates " 01/01/2017 to 01/03/2017" it should give me a error like the validation error in the right of the field screen shot for my rental car app models.py class Contra(models.Model): date_debut = models.DateField(null=True ,blank=True) heure_debut = models.TimeField(null=True ,blank=True) date_retour = models.DateField(null=True ,blank=True) heure_retour = models.TimeField(null=True ,blank=True) forms.py class ContraForm(forms.ModelForm): date_debut = forms.DateField(widget = AdminDateWidget()) heure_debut = forms.TimeField(widget = AdminTimeWidget()) date_retour = forms.DateField(widget = AdminDateWidget()) heure_retour = forms.TimeField(widget = AdminTimeWidget()) views.py class ContraCreate(CreateView): template_name = 'rentcar/contra_update.html' form_class = ContraForm model = Contra def form_valid(self, form): now_date = date.today() now_time = datetime.now().strftime('%H:%M:%S') x = Contra.objects.filter(location=self.request.user, date_debut__lte=now_date, date_retour__gte=now_date) c = form.instance.car for e in x: if c.imatriculation == e.car.imatriculation : print ("Leased car") ValidationError(_('Invalid value')) return super(ContraCreate, self).form_invalid(form) return super(ContraCreate, self).form_valid(form) -
Calling a url from one app to another in Django
How do you access a namespaced url from a template of an app where the namespaced url is located in another app? I tried "{% url 'mynamespace:url' %}" But I get NoReverseMatch and mynamespace is not a registered namespace error but I have, app_name = 'mynamespace' in the concerned app. -
shapely mapping gives error on my geometry when serializing
I am trying to serialize my object from django, one field is a polygonfield and I was using the serializer with geojson but needed to change my query set so ditched that. But when I try json.dumps it complains about not being able to serialize my polygon field, so after some googling I found mapping ? I am implementing it like this: returnData = [] secondData =[] object_list = ZoneEntity.objects.filter(cesiumentity__sensor__in=sensor).distinct('zone_number') print len(object_list) for ze in object_list: second_list = CesiumEntity.objects.filter(zone_id = ze.zone_number) returnData.append(ze.zone_number) print ze.mpoly #ask about this.. returnData.append(mapping(ze.mpoly)) #do the opposite of the mpoly to string somehow hmmmm for sl in second_list: secondData.append(sl.sensor) secondData.append(sl.resource_location) secondData.append(sl.name) secondData.append(sl.country_code) secondData.append(sl.corner_coords) secondData.append(sl.target_name) secondData.append(sl.collection_date) returnData.append(secondData) But get this error: AttributeError: 'Polygon' object has no attribute '__geo_interface__' So obviously I am missing something. This is so I can do this later: return HttpResponse(json.dumps(returnData)) #was jdata I am (probably erroneously and inefficiently) building up the returnData and secondData lists of lists so hoping I can pass back one zoneEntity object that contains a zone_number and all the other CresiumEntities with that zone_number as a json string back to my website. -
Inline bock not working with Python Django
So I have had this issue driving me crazy because I thought display: inline-block would work but it does not seem that way with Python Django. I am not sure if my css is bad or if it is my python code. I am very new at python so please excuse for how newb this may look. Template: <article class="article top-buffer {% if article.is_featured %} featured{% endif %} {% if not article.published %} unpublished{% endif %}"> {% if not detail_view %} <div class="hg-box"> <div> <img src="{% thumbnail article.featured_image 1200x400 crop subject_location=article.featured_image.subject_location %}" class="img-responsive product-main-image"> </div> <div class="post-preview hg-post"> <a href="{% namespace_url 'article-detail' article.slug namespace=namespace default='' %}"> <h2 class="post-title"> {% render_model article "title" "" "" "striptags" %} </h2> {% if article.lead_in %} <h3 class="post-subtitle"> {% if not detail_view %} {% render_model article "lead_in" "" "" "truncatewords:'20'|striptags" %} {% else %} {% render_model article "lead_in" "" "" "striptags" %} {% endif %} </h3> {% endif %} </a> {% include "aldryn_newsblog/includes/date.html" %} </div> </div> {% endif %} {% if detail_view %} {% render_placeholder article.content language placeholder_language %} {% endif %} Here is my related CSS .hg-post{background-color:white;padding:0 20px 20px 20px;border:1px solid #E6E3E8;margin-bottom:5px} .hg-box{display: inline-block} Post-Preview is just text related so I did not include … -
django forms.py unit test - testing for success?
I am running python 3.4, django 1.10, Coverage 4.3.4 and django-coverage-plugin 1.4.2. I am trying to learn unit testing and I am finding the concept very difficult. This may be a very basic question and easy to solve, but this is where I am stuck at. This is the validation code I am trying to test (I have included line numbers): #143 if 'employment_history_start_date' in cd_ehdf and cd_ehdf['employment_history_start_date'] is not None: #144 if 'employment_history_start_date' in cd_ehdf and cd_ehdf['employment_history_start_date'] > date.today(): #145 self._errors['employment_history_start_date'] = self.error_class([_("Date must not be greater than today.")]) #147 if 'employment_history_finish_date' in cd_ehdf and cd_ehdf['employment_history_finish_date'] is not None: #148 if 'employment_history_finish_date' in cd_ehdf and cd_ehdf['employment_history_finish_date'] > date.today(): #149 self._errors['employment_history_finish_date'] = self.error_class([_("Date must not be greater than today.")]) This is the forms unit test code that I have in place that tests that the dates are not greater than today. As far as I can tell, these two tests are working: def test_clean_invalid_employment_history_start_date_gt_today_when_standard_details(self): employment_history_start_date = timezone.now() + datetime.timedelta(days=100) employment_history_finish_date = timezone.now() - datetime.timedelta(days=600) cleaned_data = { 'employment_history_display_type': DISPLAY_STANDARD_DETAILS_WITH_LABELS, 'employment_history_employerTB': 'Employer', 'employment_history_suggestion_type': HIDE_SUGGESTIONS, 'employment_history_employerTA': 'Employer', 'employment_history_start_date': employment_history_start_date.date(), 'employment_history_current_employment': False, 'employment_history_finish_date': employment_history_finish_date.date(), 'employment_history_timespan_display': True, } # Set cleaned data to a copy of the dictionary, so we can assert against the … -
Django filter sort by number of ForeignKey related objects
I have a website which catalogs hikes, and users can log that they have gone on these hikes. I have a search function, and I want to be able to sort my list of hikes by the amount of times they have been completed by my users. I found this post which seems relevant, but is referring to a specific field in the foreignkey model, whereas I'd like to just count the total number of instances: Django QuerySet ordering by number of reverse ForeignKey matches Here is some sample code: models.py: class Hikes(models.Model) ... class UserLog(models.Model) user = models.ForeignKey(User, on_delete=CASCADE) hike = models.ForeignKey(Hikes, on_delete=CASCADE) I need to generate a queryset from my Hikes model that counts the number of times UserLog has referenced each hike, and then orders the hikes from most referenced to least. Something like this: Hikes.objects.order_by(for each hike, count # of references in UserLog, then place in order by # of references) So if Hike #1 has 10 UserLog instances, Hike #2 has 20, and Hike #3 has 5, the QuerySet would return: Hike #2, Hike #1, Hike #3 Any tips? -
Setting User's object's password and saving it
I am currently working on a small project, just to practice and learn Django. I've decided to at first start from creating user authentication in wide meaning of that term. I got stuck on issue with registration. I don't know what I should provide to set_password method as first positional argument, and to save method. Self argument is needed, when I am trying to type there 'request', I am getting following error: TypeError at /register/ super(type, obj): obj must be an instance or subtype of type Here's register view which I use: def register(request): if request.method == 'GET': form = UserCreateForm() return render(request, 'registration/register.html', {'form': form}) if request.method == 'POST': form = UserCreateForm(request.POST) if form.is_valid(): cd = form.cleaned_data username = cd['username'] email = cd['email'] password1 = cd['password1'] password2 = cd['password2'] user = User user.username = username user.email = email if password1 == password2: user.set_password(request, password1) user.save(request) # redirect to success page else: # return error else: # return error And here's my form's code: class UserCreateForm(forms.Form): email = forms.EmailField(required=True) username = forms.CharField(required=True) password1 = forms.CharField(max_length=32, widget=forms.PasswordInput) password2 = forms.CharField(max_length=32, widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'email', 'password1', 'password2') I'd be very appreciate if you will help me … -
Django 2.7 form.Form DateTimeField input_formats ISO 8610
I'm stuck on validate django datetime format with ISO 860 (ex: 2017-02-26T18:30:00+07:00) I try: schedule_date = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%Z'],required=True) schedule_date = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ'],required=True) but none of those are work -
DJango: Not allowing newly-created user to log in until he/she is approved by the admin?
I am recently trying to develop a website using DJango in which a person can make his/her registration in the system but he/she should not be allowed to log in the system until the admin approves the request. I tried the user.is_active field but the only thing it does is to prevent the new user to have access as admin. In other words, the system gives him/her permission to log in the system. My code is as follows: # create a new user but he will be inactive until admin's approval user = User.objects.create_user(username=username, password=password) user.is_active = False After changing the is_active field of the user to False I try to log in the system using the new user's username and password and the system lets me in. This is my code for the login: def login(request): context = RequestContext(request) username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username = username, password = password) if user is not None and request.user.is_active: auth.login(request, user) print 'login' print request.user.username print request.user.is_active return redirect('app.views.results') else: print 'no login' return render(request, 'login.html') When I print the user's username and is_active field, I see that the "is_active" field is True instead of False. … -
Django - Generate single template value, if available
What is the best way to perform this action? I want an input box in HTML to fill the value if there is a value to fill. I know this is confusing, please see the HTML and code below for clarification. NOTE: the only case in which the python code you see below is called is from another page where a user clicks a button. The instance where the 'else' part of the HTML should be valid is when the user gets to the page from another source, and the value should be blank. Python: class editProblemHanlder(BaseHandler): @user_required def post(self): self.prob_key = ndb.Key(urlsafe=self.request.get('problem_key_edit')) self.problem = self.prob_key.get() template_values = {'problem': self.problem.content, 'answer': self.problem.answer, 'keyword': self.problem.keyword} self.render_template('inProblem.html', template_values) HTML: {% if problem.content %} <input class="inproblem" type="text" id="textbox" name="problem" value="{{ problem.content }}"> {% else %} <input class="inproblem" type="text" id="textbox" name="problem" value="No Value"> {% endif %} I know this is not correct, but hopefully it gets my question across. -
Django can not access Image and Media files
When I upload my files on my server I'm getting errors (not found error) while loading images and media files. But on my computer (localhost) everything is ok. Can you help me to fix? settings.py STATIC_URL = '/site/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") STATICFILES_DIRS = os.path.join(BASE_DIR, "static"), MEDIA_URL = '/files/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media") urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('article.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) templates/index.html <div class="thumbnail"> <!--image--> <canvas class="image-canvas" style="background-image: url({{ article.cover.url }});"></canvas> <div class="caption"> <!--article head--> <h3 style="text-align: center !important;">{{ article.title }}</h3> <!--article summary--> <div class="content"><p>{{ article.content | truncatewords_html:'30' }} </p></div> </div> <div class="visible-xs line "></div> </div> -
why collectstatic does not upload modified files to S3? django
I am currently using django and uploading all my statics into S3. The problem I am having now is, uploading works perfect BUT if I have modified a file let's say uploading.js I changed something in there and do collectstatic it wouldn't upload the uploading.js again. It will just say 0 files uploaded I have to go into S3 and delete uploading.js THEN run collectstatic and it will work. This is quite bothering though. I checked a few sites, and they mentioned about uploading time locally and on S3. I have checked, the files uploaded into S3 is exactly the same timestampe locally that time doesn't seem to be the issue. Can anyone give me a hand with this issue? Thanks in advance. -
How to re populate media/cache in django
I had just upgrade an app to django 1.8 change the server. For some reason the files under media/cache are missing. Is there a way to re-generate all of that? -
'data' event is not fired on child_precess spawn in gulp when running django server
I write small gulp task which run django server const gulp = require('gulp'); const spawn = require('child_process').spawn; function runserver() { // var run = exec('python ../manage.py runserver'); var run = spawn('python', [ "../manage.py", "runserver" ]); run.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); run.stderr.on('data', (data) => { console.log(`django log: ${data}`); }); run.on('close', (code) => { console.log(`child process exited with code ${code}`); }); } gulp.task('runserver', runserver); module.exports = runserver; http logs come well from stderr. Now I want to get when the django server is acctually started. When I just run python manage.py runserver, this message is appeared first. Performing system checks... System check identified no issues (0 silenced). February 25, 2017 - 05:57:55 Django version 1.10.4, using settings '' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. If task can catch this messages it means the django is started. But run.stdout.on doesn't send me any lines. How can I catch stdout messages? -
Openpyxl: column width not work correctly on windows
I use openpyxl library on my backend server(Ubuntu 64bit) for generating excel documents with a bit of styles and it well working when user open generated file in Linux. If someone open file on Windows column width are crashed. How to make that excel styles making in openpyxl well working both on Linux and Windows? A bit Example how it shows the file: On linux and Windows I count on your help :) -
Django - How to restrict Foreign Key choices to a ManyToMany field in another model
I have 3 models: Championship, Team and Match. Championship and Team are related with a ManyToManyField because each team can participate in multiple championships and each championship has many teams. And each match should be linked to a championship but also to 2 teams that are in the championship. class Championship(models.Model): name = models.CharField(max_length=100) teams = models.ManyToManyField(Team) class Team(models.Model): name = models.CharField(max_length=100) class Match(models.Model): championship = models.ForeignKey(Championship) team1 = models.ForeignKey(Team) team2 = models.ForeignKey(Team) score1 = models.PositiveIntegerField() score2 = models.PositiveIntegerField() I would like to ensure that 'team1' and 'team2' are in 'championship'. And also that 'team1' and 'team2' are different. How could I do that ? Maybe i could use something like Django-smart-selects but i would prefer to avoid using a third-party app. -
Using Model.object.filter(field='??') to return all in Django
So I'm building a search function for my django app. I have a request.GET form from which I'm pulling variables to plug into various filters in my model. My current setup is as follows: views.py: def search(request): grade = request.GET.get('g', '') test = Hike.objects.filter(difficulty=grade) return render(request, 'hikes/hike_list.html', { 'test': test, }) So I have users select the difficulty of the hike they are searching for from a multiple choice box, and that plugs into my filter (where difficulty is a field of the Hike model). However, I want an option to not use this filter, and return all (so from the multiple choice box, the user would select "All"). What do I plug in to the filter in order for that filter to be ignored (or just return all)? Or is there a better way to structure this?