Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get current model instance in related ModelForm
If I have the following Model, ModelAdmin and ModelForm, how do I get current Order in clean method class Order(models.Model) # Order Model class OrderAdmin(admin.ModelAdmin): form = OrderAdminForm class OrderAdminForm(forms.ModelForm) class Meta: model = Order def clean(self): # How do I get current Order here ? admin.site.register(Order, OrderAdmin) -
Create an Object with many to many field Django
I need to create a property object with many to many fields. I have many to many fields objects preference_get I'm not able to understand how would I add and save Preference to property object. views.py for p in preference_list: preference_get=Preference.objects.get(id=p) print(preference_get) new_property = Property.objects.create(name=str(property_type) + str(" - ") + str(property_status), created_at=timezone.now(),location=loaction_title, status=1, budget=price,bhk=property_type_get,furnish=furn_obj, lat=lat, lng=lng, owner_id=request.user.id) Models.py class Property(models.Model): name = models.CharField(max_length=500) owner = models.ForeignKey(OwnerInfo, on_delete=models.CASCADE) location = models.CharField(max_length=1000) status = models.IntegerField(blank=True, null=True, default=1) rating = models.IntegerField(blank=True, null=True, default=5) created_at = models.DateField(blank=True, null=True) budget = models.CharField(blank=True, null=True, max_length=500) furnish = models.ForeignKey(Furnish, on_delete=models.CASCADE, blank=True, null=True) bhk = models.ForeignKey(Bhk, on_delete=models.CASCADE, blank=True, null=True) preference = models.ManyToManyField(Preference) class Preference(models.Model): preference = models.CharField(max_length=30) -
Django: Render external static HTML, CSS and JS
I'd like to display a pre-generated but external static HTML in my django web app. The page I want to display exist as a folder with the following structure: map_example/ |--- index.html |--- images/ |--- layers/ |--- resources/ |--- styles/ |--- webfonts/ The data and styles for each page is unique and created by other users, so creating them inside the web app is not an option. For now, I'm storing the files in a zip inside a FTP and I'm able to download and extract it to a temporary folder or my media folder inside the django app. The problem is how do I ask django to render the index.html while keeping the references to the JS and CSS files in the other folders in the structure? I think it's possible to render static HTML stored in the "static" folder inside Django, using: {% static 'path/to/index.html' %} but (as far as I understand), I cannot store new files there during production (since that's what the "media" folder is for). I could read the HTML and pass it to the template to be rendered, but then what about the .js, .css, .png and .ttf files that are referenced in the … -
Django Setup on New Systems: No Such Table auth_user
Every time I am setting up our Django project in a new environment and trying to start the server (makemigrations or migrate or runserver same behaviour), I am getting the error message django.db.utils.OperationalError: no such table: auth_user. I am assuming this comes from using the user model as a foreign key in some of our models (see below) and as a new system is set up (no database created yet, Django default config atm) Django tries to create the table for our custom model and fails because of the foreign key (user table) as it is not created yet. # Model for projects (example) class Projekt(models.Model): project_name = models.CharField(max_length=100, unique=True) project_manager = models.ForeignKey(User, related_name="Manager", on_delete=models.DO_NOTHING) My question is: is there any best practice on what to do to prevent this? For now, we are just copying the database from our running systems for every new developer we are getting, but that seems very wrong... Sitenote: We are excluding __pycache__/, the migrations/ folder and the __init__.py from our git repository. Could this have anything to do with the problem? I tried different solutions already, some (like here on SO or here) said, I sould write an exception, if the table is … -
How to run a docker project through github code?
I have a django web application code in github. From time to time, I make necessary updates and arrangements on the repository. I have to pull the project every time and make adjustments on the docker and run on my machine. Is there a way to run docker synchronously with the code in my github repoitory? When I make a change in github I want the docker to pull it automatically and try to run the project without interrupting. -
Django: add values to a manytomanyfield that are not in the database from frontend form
I have a manytomanyfield called certifications and i will like logged in users enter values which will be created and added to the database (and not from the admin). Is there a plugin for this... if not any lead on how i can go about this will be appreciated. I tried this select2 plugin but it didn't work class MyModelSelect2TagWidget(ModelSelect2TagWidget): queryset = MyModel.objects.all() def value_from_datadict(self, data, files, name): values = super().value_from_datadict(self, data, files, name) qs = self.queryset.filter(**{'pk__in': list(values)}) pks = set(str(getattr(o, pk)) for o in qs) cleaned_values = [] for val in value: if str(val) not in pks: val = queryset.create(title=val).pk cleaned_values.append(val) return cleaned_values -
django - using a foreign key as a link
So I've got a bit of an issue with how to get a certain value from a foreign key in my project. my models.py class Category(models.Model): category_name = models.CharField(max_length=50) def __str__(self): return self.category_name class Frame(models.Model): banner = models.CharField(max_length=50) description = models.TextField(null=False, blank=False) date_created = models.DateTimeField(default=datetime.now, editable=False) user_id = models.ForeignKey(User, null=True, related_name='+', on_delete=models.CASCADE) category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) def __str__(self): return str(self.banner) my urls.py app_name = 'frames_app' urlpatterns = [ path('frame-<int:pk>', views.single_frame, name='f_detail'), path('category/<str:category>', views.category_filter, name="f_category") ] my views.py def category_filter(request, category): frames = Frame.objects.filter(category=category) return render(request, 'frames_app/category_frames.html', { 'frames': frames }) my html file {% for frame in frames %} <h2><a href="{% url 'frames_app:f_detail' pk=frame.pk %}">{{frame.banner}}</a></h2> <p>{{frame.ad_description}}</p> <p><a href="{% url 'frames_app:f_category' category=frame.category %}">{{frame.category}}</a></p> <p>Dated {{frame.date_created}}</p> {% endfor %} I get this error when i try to access the page: invalid literal for int() with base 10: 'somecategory' 'somecategory' being an category object. So how would i be able to access just the category_name to pass to django instead of passing the whole object, as seems to be the case. -
ModuleNotFoundError in django with python 3.7 and xampp 3.2.2
I have a problem with my current django-website. When I run my app with http://localhost/homepage I get the following error: [Sun Oct 21 13:43:22.384951 2018] [ssl:warn] [pid 1744:tid 756] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name [Sun Oct 21 13:43:22.459176 2018] [ssl:warn] [pid 1744:tid 756] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name [Sun Oct 21 13:43:22.501166 2018] [mpm_winnt:notice] [pid 1744:tid 756] AH00455: Apache/2.4.33 (Win32) OpenSSL/1.1.0h mod_wsgi/4.6.4 Python/3.7 PHP/7.2.7 configured -- resuming normal operations [Sun Oct 21 13:43:22.501658 2018] [mpm_winnt:notice] [pid 1744:tid 756] AH00456: Apache Lounge VC15 Server built: Mar 28 2018 12:12:41 [Sun Oct 21 13:43:22.501658 2018] [core:notice] [pid 1744:tid 756] AH00094: Command line: 'C:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache' [Sun Oct 21 13:43:22.510936 2018] [mpm_winnt:notice] [pid 1744:tid 756] AH00418: Parent: Created child process 5932 [Sun Oct 21 13:43:23.325421 2018] [ssl:warn] [pid 5932:tid 788] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name [Sun Oct 21 13:43:23.394264 2018] [ssl:warn] [pid 5932:tid 788] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name [Sun Oct 21 13:43:23.505603 2018] [mpm_winnt:notice] [pid 5932:tid 788] AH00354: Child: Starting 150 worker threads. [Sun Oct 21 … -
How to map Django html templates for the browser?
I am converting my Django project to a progressive web app, and i am trying to precache my my files for them to be available offline. My problem is, I dont know how to locate my templates (e.g. homepage.html, index.html) to precache them using my service worker. I placed my service worker inside the static folder. My current folder structure looks like this: main/ -- migrations/ -- static/ ---- js/ ------ core/ ------ plugins/ ------ app.js ---- css/ ---- img/ ---- templates/ ------ base.html ------ about.html ------ homepage.html ----*serviceWorker.js* -- __init.py__ -- admin.py -- apps.py -- models.py -- views.py my_second_app/ -- migrations/ -- static/ ---- js/ ------ index.js ---- css/ ---- img/ ---- templates/ ------ base.html ------ user.html ------ page.html -- __init__.py How can I map the HTML templates for my main app and my_second_app on my serviceWorker.js inside the static folder? Thanks in advance for anyone who could help. And let me know if I am doing it wrong :) Anyway, I have successfully precached the static files. This is my code sample. -
How to get the field value that is excluded in order to change the row background
I want to display a table in which some fields are excluded, because I do not want to display them in a table. At the same time, I want to change the color in the row based on the values that are excluded. Is it possible to do this with django-table2 ? import django_tables2 as tables from web_logic.models import Stations from django_tables2.utils import A class StationTable(tables.Table): """ """ station_id = tables.LinkColumn() rack_sum = tables.LinkColumn("racks_page", args=[A('pk')], verbose_name='Кол-во стоек') status = tables.BooleanColumn() def __init__(self, *args, **kwargs): super(StationTable, self).__init__(*args, **kwargs) def render_station_id(self, value): print(value) return "%s " % value class Meta: model = Stations exclude = ( "id", "onboot_time", 'certificat_key', 'private_key', "status", "ipadress", 'latitude', 'longitude', ) template_name = 'django_tables2/bootstrap.html' attrs = { "class": "table", "td": {"class": "table-hover",}, "thead": {"class": "table-dark"}, } For example, the status field describes a state for the entire row. It can be True or False. I do not want to display the column with this field, but I want to highlight (change the color of the line) based on the value for this field. How can i do this ? -
Bootstrap modal does not display properly
I am creating a modal which should be displayed when clicked on a table row. When i am using Bootstrap 2.x it displays properly, but when using Bootstrap 3.x the modal moves in extreme left of laptop display and is only viewed half. I am not good at designing, can someplease help me with this issue. <div class="modal fade" id="test-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> </div> <div class="modal fade" id="monitor-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> </div> $("#tableId").on("click", "tr", function(e) { $("#tableId").find("tr.highlight").removeClass("highlight"); $(this).addClass("highlight"); columns = e.currentTarget.getElementsByTagName("td"); isSelectedMachineVacant = columns[columns.length-1].childNodes[0].className.indexOf("label-success") > -1 if (isSelectedMachineVacant) { $("#temp").val(""); $("#fan-val").val(""); $("#heater-val").val(""); $("#test-modal").modal(); } else { $("#monitor-modal").modal(); getLogs(); } }); -
How to add upload images option via local/PC/browse on TinyMCE in a Django website?
I have added TinyMCE editor to my website and can't find the option to allow users to insert images via local machines using the browse option on the device. Pip package used - django-tinymce4-lite. These are the settings from settings.py file: TinyMCE editor setting variables TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True,} -
get_context_data in mixin not being called
I'm new to Django. I want to use a mixin to return some data to multiple class based views. It seems the get_context_data I defined in mixin is not called in the view class. class MyMixin(object): def get_context_data(self, *args, **kwargs): data = super(MyMixin, self).get_context_data(*args, **kwargs) from django.utils import timezone data['object'].now = timezone.now() return data class PageDetail(DetailView, MyMixin): model = MyModel template_name = 'page-detail.html' def get_context_data(self, *args, **kwargs): data = super(PageDetail, self).get_context_data(*args, **kwargs) return data -
Making sure a field is always null in Django
I have a parent class which is being extended by 3 different models. The parent class has a field called foo lets say, and this field needs to be always null for one of the sub-classes. How can I ensure this? Right now, I am using null=True, and editable=False constraints. However, these can be circumvented from the shell or an API if the field is exposed during object creation. class ThirdSubclass(ParentClass): # Over-ridden field from abstract parent class foo = models.PositiveIntegerField(blank=True, null=True, editable=False) I am also using the PositiveIntegerField since I want to allocate as little space as possible for this field. Anyway, how do I do this? Is over-riding the save method the only option? Ideally, I would love something within the field definition. Thanks! -
() missing 1 required positional argument: 'id'
I keep getting an error when trying to display individual items. This is my code, i hope its understandable. my urls page: urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/', views.aboutus, name='aboutus'), url(r'^specialoffers/', views.offers, name='offers'), url(r'^contactus/', views.contact, name='contact'), url(r'^excursions/', views.excursions, name='excursions'), url(r'^singleexcursion/<int:id>/', views.singleexcur, name='singleexcur'), url(r'^booking/', views.booking, name='booking'), url(r'^confirmation/', views.confirming, name='confirming'), url(r'^payment/', views.payment, name='payment'), ] My views page: def singleexcur (request,id): excur = Excursion.objects.get(id = id) return render(request, "excursions/single.html", {"excur": excur }) my error: TypeError at /singleexcursion/<int:id>/ singleexcur() missing 1 required positional argument: 'id' -
I want to add costume field after django social app login
Hi I am php developer new to python/django I'm creating a social login with django using 'social-auth-app-django' library and i followed following tutorial to implement it. https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html Its working fine but i also need to add costume files in database which will be in different table but it will be get added when new user is created. I have extended the user table as following from django.contrib.auth.models import User class NewsCreator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) CreatorLastLogs= models.CharField(max_length=100) CreatorLogs= models.CharField(max_length=100) and i want to add data to these fields when a new user is created or when existing user logins. I tried going through documentation but could not found any thing that is related to code extension/customisation etc. Thanks in advance -
'utf-8' codec can't decode byte 0x97 in position 14: invalid start byte
I want to download one directory from my server on button click. The directory should be downloaded in zip format. I am using Django and Python. I tried this earlier with the same code but it was on Python2 venv. The same code on Python3 venv gives utf-8 codec can't decode byte error. The zip of the directory is created successfully but when i press the download button on my website it throws me above error. @login_required def logs_folder_index(request): user = request.user if not is_moderator(user): raise Http404("You are not allowed to see this page.") else: if os.path.exists('Experiments.zip'): os.remove('Experiments.zip') zipf = zipfile.ZipFile('Experiments.zip','w',zipfile.ZIP_DEFLATED) path = settings.BASE_DIR + '/experiments/' zipdir(path,zipf) zipf.close() zip_file = open('Experiments.zip','r') response = HttpResponse(zip_file, content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="{0}"'\ .format(Experiments.zip) return response Can someone please help me with this problem. -
Django concat F function with character
I have a model which has group_id CharField. This field should equal object's pk with '#' prefix. I'm trying to update database in such way. MyModel.objects.update(group_id=f'#{F("pk")}') But this doesn't work. In fact, it sets #F(pk) string for all objects. Can I do this operation using F function? -
How do I format a read-only field in the Django admin with a 3rd party library?
I am using django-prettyjson to format my JSONFields in the admin. My code is setup as follows: models.py class MyModel(models.Model): structure = JSONField(default=dict, blank=True, null=True) static_structure = JSONField(default=dict, blank=True, null=True, editable=False) admin.py class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { JSONField: {'widget': PrettyJSONWidget } } def get_readonly_fields(self, request, obj=None): if obj: return ('static_structure') else: return super(TableAdmin, self).get_readonly_fields(request, obj) admin.site.register(MyModel, MyModelAdmin) In other words, one of the JSONFields is not editable and read-only. It appears on my admin panel, but its not being affected by the widget which renders the other field as formatted JSON. Any way to fix this? Looking through plain-text JSON data is a complete drag. Thanks! -
Why middleware mixin declear in django.utils.deprecation.py
in path django.utils.deprecation.py we have some class about deprecation warning for methods. very nice. in that file we have a class called MiddlewareMoxin. this class used to write middleware classes. Although not related to deprecation, Why this class wrote in this path? sorry for my bad English. -
Proper way to have a nested writable serialization django drf
Assum that I have two models with two serializers, one has another as a nested serializer, as shown below: class Item(models.Model): ... discounts = ManyToManyField(Discount) gift_discounts = ManyToManyField(GiftDiscount) ... class Billing(models.Model): ... items = ManyToManyField(Item) ... # serializers class ItemSerializer(serializers.ModelSerializer): ... def create(self, validated_data): discounts = validated_data.pop('discounts') gift_discounts = validated_data.pop('gift_discounts') item = super(ItemSerializer, self).create(**validated_data) for discount in discounts: item.discounts.add(discount) for gift_discount in gift_discounts: item.gift_discounts.add(gift_discount) class BillingSerializer(serializers.ModelSerializer): items = ItemSerializer(queryset=Item.objects.all(), many=True) ... def create(self, validated_data): items = validated_data.pop('items') billing = super(BillingSerializer, self).create(**validated_data) for item in items: discounts = item.pop('discounts') gift_discounts = item.pop('gift_discounts') sell_item = Item.objects.create(**item) for discount in discounts: sell_item.discounts.add(discount) for gift_discount in gift_discounts: sell_item.gift_discounts.add(gift_discount) As you can see for such a scenario I had to write twice a same code for creation of item one in item serializer and another in billing serializer, this is against the DRY rule and it could getting more complicated and bug prone as code advances. I am looking a way to write this code just once and use it in both places. Maybe having a class method in ItemSerializer is a solution but not complete solution there you have not many ItemSerializer methods and members which you may need.I think the best possible solution … -
Using Django setup to serve static files from development server, but images won't display
I have my settings.py configured correctly, all templates load ok, and from what I can tell all images should load just fine. This is an example of the HTML generated by Django when viewing page source, served via the development server: < img src="/static/images/icons/logo.png" alt="IMG-LOGO"> When I access that path directly in the browser, i.e. DEVSERVERIP:PORT//static/images/icons/logo.png The image loads without issue. The last time I made a site with django I was not aware static files were not served by default, and when trying to access the path of an image it would not load at all, so this appears to be a different issue. Instead, where the logo should be, HTML is output for some reason: My Django settings, template code, image paths etc all seem correct, and I can access the images specified as the source to the img tags without issue. How can I troubleshoot this to see what the problem is? -
I am trying to send exceptions also but it is giving me syntax error
errors: File "/home/soubhagya/Desktop/carrier-circle/backend/details/urls.py", line 2, in <module> from .views import * File "/home/soubhagya/Desktop/carrier-circle/backend/details/views.py", line 298 return {"code":402,"error":except} ^ SyntaxError: invalid syntax codes: try: api = Details.get_important_links( "OdishaGovtJobs", "OdishaGovtJobDetails", "state-govt-jobs/odisha-govt-jobs" ) return JsonResponse(api,safe=False) except: return {"code":402,"error":except} I am trying to send exceptions along with status code but it is giving me syntax error -
Django-tables2: Argument of type 'XX' not iterable in Checkboxcolumn
I have model of guests. class Guests(models.Model): field1 = models.Charfield(...) ... fail = models.BooleanField(default=False) Also I have table of guests. But I want to have checkboxcolumn in there, that refers to fail field. class CheckBoxColumnWithName(tables.CheckBoxColumn): @property def header(self): return self.verbose_name class GuestsTable(tables.Table): *other fields* mistake = CheckBoxColumnWithName(accessor="pk", orderable=False, verbose_name='fail123', checked='fail') class Meta: model = Guests template_name = 'django_tables2/bootstrap4.html' fields = (*other fields*, 'mistake') And problem in checked, because when I try to add smth there - I get a mistake argument of type 'Guests' is not iterable **** ..site-packages\django_tables2\columns\checkboxcolumn.py in is_checked, line 87 87: if checked in record: And I can't understand how to declare 'checked' right, cause I tried dict, list, tables.A('fail') like in linify column - same result. Also in docs said, that I can't select several checkboxes and do smth with that, is that concern that part or not? -
My web page takes longer time to load after adding json layers
So I am trying to develop something using leaflet. But I want to allow users to be able to overlay couple of my json layers (example a layer showing hospitals and restaurants) on my original web map. Unfortunately, doing so it made my web page slower than you can imagine. What could be the problem or is there a way that I can load couple of json on my web page faster. this is how I load them: - ** ** ** **