Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a save method in an abstract model that checks whether an instance exists?
I have the following models: class PlaceMixin(models.Model): name = models.CharField(max_length=200, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) sublocality = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) class Bar(PlaceMixin): pass class Restaurant(PlaceMixin): pass Bar and Restaurant have almost same save() method: def save(self, *args, **kwargs): try: bar = Bar.objects.get(id_google=self.id_google) except Bar.DoesNotExist: Do something super().save(*args, **kwargs) def save(self, *args, **kwargs): try: restaurant = Restaurant.objects.get(id_google=self.id_google) except Restaurant.DoesNotExist: Do something super().save(*args, **kwargs) I was wondering if I can put the method in the Abstract model and pass it to the two inherited model? def save(self, *args, **kwargs): try: temp = self.objects.get(id_google=self.id_google) except self.DoesNotExist: Do something super().save(*args, **kwargs) Something like this? But you can query in an abstract model. I basically need to check if an instance exists for executing an action. -
assertRaises won't raise ValidationError
When testing an ImageField with an invalid file passed to it, Django is asserting that no ValidationError is being raised. This is being done in a with self.assertRaises context. However, when I access form.errors.as_data() it shows that a ValidationError is technically being raised. I'm not clear on what is happening. #tests.py from django.core.exceptions import ValidationError class SubmitProfileForm(TestCase): @classmethod def setUpTestData(cls): cls.data = { 'email': 'test@email.com', 'birth':'2019-01-01', 'coding_level': 'Hobbyist', 'bio': 'About me...', 'github': 'http://www.github.com', } cls.image = open(join(dirname(__file__), 'images/test_file.txt'), 'rb') cls.file = { 'avatar': SimpleUploadedFile( name=cls.image.name, content=cls.image.read() ) } def test_invalid_file_uploaded(self): with self.assertRaises(ValidationError): form = ProfileForm(self.data, self.file) form.errors print(form.errors.as_data()) # forms.py class ProfileForm(ModelForm): class Meta: model = Profile fields = ( 'email', 'birth', 'coding_level', 'bio', 'github', 'avatar' ) # models.py class Profile(models.Model): hobby = "Hobbyist" develop = "Developer" coding_level = ( (hobby, hobby), (develop, develop) ) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) email = models.EmailField() birth = models.DateField(verbose_name="Date Of Birth") coding_level = models.CharField( verbose_name="Experience", max_length=20, choices=coding_level, default=hobby, blank=False ) bio = models.TextField( verbose_name="User Bio", validators=[MinLengthValidator(10, message="Add more to your bio!")] ) github = models.URLField( verbose_name="GitHub link", validators=[check_submitted_link], unique=True ) avatar = models.ImageField(upload_to="images/%Y/%m/%d/") Actual result: print(form.errors.as_data()) '''{'avatar': [ValidationError(['Upload a valid image. The file you uploaded was either not an image or a β¦ -
Trouble understanding axios error handling in react
I am learning about react and django. I have installed django-rest-auth to handle account creations and authentication for users. I also wanted to learn about react and I have install axios to make http request to my django rest api. I want to have a "splash" page where users would first access the site. If the user is already logged in they'll see their profile and other content. If the user isn't logged in they should be presented a login page. Here's my App.js code I have so far. import React, { useState, useEffect } from 'react'; import axios from 'axios'; import logo from './logo.svg'; import './App.css'; function LoginPage(props) { console.log('LoginPage props are:'); console.log({ props }); return (<div className="LoginPage">props are: {props}</div>) } function SplashPage(props) { const [currentUser, setCurrentUser] = useState(null); console.log('SplashPage props are:'); console.log({ props }); const userUrl = 'http://localhost:8000/rest-auth/user/'; console.log('userUrl is:' + userUrl); axios.get(userUrl) .then(res => { setCurrentUser(res.data); }) .catch((error) => { console.log(error.response); return (<div><LoginPage /></div>); }) return (<div className="SplashPage">[{userUrl}] [{currentUser}] </div>); } function App() { return ( <div> <SplashPage /> </div> ); } export default App; Heres my index.js file: import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker β¦ -
How to change the value of an attribute in another class when performing a Post Django
I am making a Sale where with a Foreignkey I obtain an order by selecting it, this order has a status of "Pending", what I want is that when making a sale with all the necessary data entered, store those values ββin the database and at the same time update the order status value, which is in another table. This is my Sale Model: class Venta(models.Model): fecha = models.DateField(default=datetime.now, null=True, blank=True) pedido = models.ForeignKey(Pedido, db_column='pedido_id', on_delete=models.SET_NULL, null=True) total = models.CharField(max_length=200, default=1) cliente = models.CharField(max_length=100) nit = models.CharField(max_length=10) def get_absolute_url(self): return reverse('control:venta-detail', args=[str(self.id)]) def __str__(self): return str(self.id) Order Model: class Pedido(models.Model): total = models.DecimalField(max_digits=10, decimal_places=2, default=0) fecha = models.DateField(default=datetime.now, null=True, blank=True) estado = models.CharField(max_length=20, default='Pendiente') def get_absolute_url(self): return reverse('control:pedido-detail', args=[str(self.id)]) def __str__(self): return str(self.id) and the View to create a new Sale: class VentaCreate(CreateView): model = Venta form_class = VentaForm success_url = reverse_lazy('control:ventas') template_name_suffix = '_crear' @method_decorator(permission_required('control.add_venta',reverse_lazy('control:ventas'))) def dispatch(self, *args, **kwargs): return super(VentaCreate, self).dispatch(*args, **kwargs) And in what I have investigated in my view I tried this: def estado_pedido(request, pk): pedido = get_object_or_404(Pedido, pk=pk) if request.method=='POST': pedido.estado = "Finalizado" pedido.save() But I don't know how to pass the id of the selected Order, and I don't know what I should "return" -
Please help me with my dilema - Did I miss some valuable info or my employer wanted too much on Python Junior interview?
Here is some non-tech question from newbie Python programmer. So today I did first try to take a job. Employer called me and started first interview. He asked some basic questions like whats a difference between list and set etc., But then he asked me how actually Float type works in Python. He meant not like how float() method work but how actually Python stores and handle float variable "under the hood". I couldnt anwser that because I have never met such info and never even had a clue to learn that. And immidiately I got rejected. Btw I use Python almost everyday along with Java. I do undarstand all basics and OOP stuff, including some of patterns. I do have three crossplatform projects on Python/Kivy, who use internet sync, Pusher and openCV API, so I guess Im not total noob here. So my question to you guys - is that me missing some valuable info or my employer asked a hard question for a Junior programmer? Thank you for you attention. Please if you know what am I missing please hit me with it right in my face -, its really important for me :) -
How to create multiple graph by json element in d3.js
I am trying to generate multiple graph by each json element's name with d3. I think I could use plain javascript array filter function but I'm not entirely sure on how to implement that. So I have https://i.imgur.com/X4AFyfD.png but I want something like https://i.imgur.com/kmqfWDr.png where each graph is a selected event. I thought about making multiple table in my database for each events but I think its better to work with large data rather than multiple smaller ones. I've read https://medium.com/turo-engineering/react-meets-d3-6a40881d0d73 but I'm not sure if I can apply it to my project. This is also running django and react and using webpack. scatterPlot.js file import * as d3 from 'd3'; (function() { var margin = { top: 20, right: 20, bottom: 30, left: 40 }, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var xValue = function(d) { return d.bweight; }, xScale = d3.scaleLinear().range([0, width]), // value -> display xMap = function(d) { return xScale(xValue(d)); }, xAxis = d3.axisTop(xScale); var yValue = function(d) { return d['total']; }, yScale = d3.scaleLinear().range([height, 0]), // value -> display yMap = function(d) { return yScale(yValue(d)); }, yAxis = d3.axisLeft(yScale); var cValue = function(d) { return d.event; }, β¦ -
Gmail + Django SMTP: "smtplib.SMTPServerDisconnected: Connection unexpectedly closed"
When following this I receive this error smtplib.SMTPServerDisconnected: Connection unexpectedly closed , and I notice none of my Django SMTP requests are working? I enabled insecure applications on my Google account already. Please help. -
Using property of related object to dynamically produce argument for ImageField
I have a model called Image that has a foreign key to another model, Tag. I want to dynamically generate the upload_to argument for the ImageField. Here is the Tag model: class Tag(models.Model): ... @property def image_path(self): # joins the hierarchy as a relative path from media folder # ['doberman', 'dog', 'animal', 'null'] --> 'images/animal/dog/doberman/' return '/'.join(['images'] + self.tag_hierarchy[-2::-1]) + '/' ... And the Image model class Image(models.Model): featured_tag = models.ForeignKey( to=Tag, null=False, blank=True, default=get_object_or_404(Tag, name='null'), on_delete=models.CASCADE ) image = models.ImageField( # I want to access the object directly and obtain the path upload_to=featured_tag.image_path # AttributeError: 'ForeignKey' object has no attribute 'image_path' ) ... How would I dynamically generate the path for the upload_to argument? -
How to make recursive django admin inline relationships
I need to create an arbitrarily deep modular structure using Django admin. The nested_admin package has gotten me part of the way there, but there's a key piece of functionality that's still eluding me β the ability to create an object B inline off object A and then create another object A off that instance of object B. Here's a closer look at my models (simplified): class ChatConditional(models.Model): triggering_question = models.ForeignKey( 'texts.MessageChain', on_delete=models.CASCADE, ) keyword = models.CharField(max_length=50, blank=False, null=False) keyword_response = models.ForeignKey( 'texts.MessageChain', related_name='keyword_answer', on_delete=models.CASCADE, ) class MessageChain(models.Model): conditional_trigger = models.ForeignKey( 'texts.ChatConditional', blank=True, null=True, ) message = models.TextField(max_length=160, blank=True, null=True) So in the admin, I want to be able to create a ChatConditional to serve as a response to a certain MessageChain. Then once I create that Conditional, create another MessageChain to send that will potentially link to another Conditional. Here's what my admin models look like: class SMSConditionalAdmin(nested_admin.NestedStackedInline): model = ChatConditional extra = 0 fk_name = "trigger" inlines = [SMSChainAdmin] class SMSChainAdmin(nested_admin.NestedStackedInline): model = MessageChain extra = 0 inlines = [SMSMessageAdmin, SMSConditionalAdmin] And now you can likely see the problem: In order to fully define the SMSConditionalAdmin, I need to set up an inline relationship to SMSChainAdmin, and vice β¦ -
Running Django unittests on PostgreSQL
I'm trying to switchover a Django unittest suite to use PostgreSQL as its backend. Changing the Django test settings was finally trivial, but now I'm getting a lot of subtle errors when the tests load fixtures. After hours of tinkering, I found the problem was because Django's not resetting the id counters on the tables, so even though all rows are deleting from each table between tests, all new fixtures don't use the Id's in the fixture but instead us an Id that's 1 plus the maximum Id used in the last test. Very frustrating. So I dug through the code to see why this was happening, and if it was a bug in my usage of Django 2.2, and I found the django.test.TransactionTestCase even has a nifty little _reset_sequences() method for resetting all table sequences between tests. However, I'm using the standard django.test.TestCase, and for some reason, in the _fixture_setup() method, it explicitly disables _reset_sequences() and assert an error: AssertionError: reset_sequences cannot be used on TestCase instances if you try to call it. Why is this? As is, Django's failing to reset table counters, and is breaking my unittests. Why can't table sequences be reset in the standard TestCase? -
DJango data migration not creating and deleting records
I have an application that manages services as a platform. A Customer has many Programs. A Code has Foreign Keys Customer and Program. They both can be null. I need to create a copy of each Code-with-no-program for each Program and delete the former afterwards. So with that in mind currently I am running this migration: # Generated by Django 2.2.4 on 2019-10-17 18:29 from django.db import migrations def code_update_program(apps, schema_editor): Code = apps.get_model("projects", "Code") Program = apps.get_model("projects", "Program") Customer = apps.get_model("customers", "Customer") db_alias = schema_editor.connection.alias for customer in Customer.objects.all(): old_codes = Code.objects.using(db_alias).filter(customer=customer, program=None) for program in Program.objects.filter(customer=customer): Code.objects.using(db_alias).bulk_create( [ Code( program=program, customer=customer, key=c.key, value=c.value, description=c.description, ) for c in old_codes ] ) old_codes.delete() class Migration(migrations.Migration): dependencies = [ ("projects", "0048_project_program_add_related_query_name"), ("customers", "0032_customer_plan_refactor"), ] operations = [migrations.RunPython(code_update_program)] ./manage.py migrate will do everything successfully, but when I verify the state of my data, the data is still the same! So it's not working. Any pointers are kindly appreciated. -
Link to child to parent in Django model
I have a Place Model: class Place(models.Model): name = models.CharField(max_length=200, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) sublocality = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) admin_area = models.CharField(max_length=100, null=True, blank=True) country = models.CharField(max_length=100, null=True, blank=True) postal_code = models.CharField(max_length=100, null=True, blank=True) region = models.CharField(max_length=1000, choices=REGION, null=True, blank=True) longitude = models.CharField(max_length=20, null=True, blank=True) latitude = models.CharField(max_length=20, null=True, blank=True) id_google = models.CharField(max_length=200, null=True, blank=True) website = models.CharField(max_length=2000, null=True, blank=True) icon = models.CharField(max_length=200, null=True, blank=True) adr_address = models.CharField(max_length=500, null=True, blank=True) date_created = models.DateTimeField(_('date created'), default=timezone.now) date_modified = models.DateTimeField(_('date_modified'), auto_now=True) Originally I create place to save information about a city, like San Francisco or New York. Now I want to create a new model called Bar: class Bar(Place): location = models.OneToOneField(Place, verbose_name=_('location'), related_name='bar', blank=True, on_delete=models.PROTECT, parent_link=True) date_inception = models.DateField(null=True, blank=True) date_closed = models.DateField(null=True, blank=True) I would like to link the bar to a particular city in the Place model. So I'm linking one row of the an inherited model with its parent. Can I avoid creating a city model and the Bar should Foreignkey into? Is this doable? If so, how do I do it? -
Receiving error when trying to instal Heroku packages
When I am trying to install the required packages for deploying my project (Learning Log) to Heroku, it keeps giving me this error: Josephs-MacBook-Pro:learning_log joseph$ source ll_env/bin/activate (ll_env) Josephs-MacBook-Pro:learning_log joseph$ pip install psycopg2==2.7.* DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Collecting psycopg2==2.7.* Downloading https://files.pythonhosted.org/packages/c2/a0/ba2c28c13bce130f971158da8fc03c231ce7778a89935eb1c3e3e6437e7c/psycopg2-2.7.7-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (1.5MB) |ββββββββββββββββββββββββββββββββ| 1.5MB 1.3MB/s Installing collected packages: psycopg2 ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/psycopg2-2.7.7.dist-info' Consider using the `--user` option or check the permissions. (ll_env) Josephs-MacBook-Pro:learning_log joseph$ -m pip install psycopg2==2.7.* -bash: -m: command not found I don't know why it keeps saying python 2.7 as I downloaded python3 and have been using it the whole time. Also when I tried running the server yesterday for Learning Log it would not work (it was running fine before). I eventually re-downloaded python3 bootstrap4 and django(in the environment) and got run server to work. side note: I have to type the 3 at the end of python3 β¦ -
How to add another 'Add +' button with custom URL in Django Admin
I have a model list page in /admin of my Django project. On the top right corner, there is a button to add a new object. I wish to create a new button right next to it, which takes me to my custom form. How can this be done? "Add Category +" on the top right corner I have tried editing overriding Django Admin Templates No success there. -
Django Crispy Form - Populate For after submit
I'm building a django app. I'm trying to re-populate the form after submit with the same submitted data. I'm using crispy form. It's not working. Below is my code. I would really appreciate any help. # models.py class Group(models.Model): group_name = models.CharField(max_length=220) group_location = models.CharField(max_length=220) # forms.py class CreateGroup(forms.Form): group_name = forms.CharField(label='Group Name', widget=forms.TextInput(attrs={'placeholder': 'Group Name'})) group_location = forms.CharField(label='Group Location', widget=forms.Textarea(), required=False) # views.py def create_group(request): title = "Create New Group" if request.method == 'POST': form = CreateGroup(request.POST) if form.is_valid(): print(form.cleaned_data) return render(request, 'create_group.html', {'title': title, 'form':CreateGroup, 'form_data': form.cleaned_data}) else: form = CreateGroup return render(request, 'create_group.html', {'form': form, 'title': title}) # create_group.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block body_content %} <div class="container-fluid"> <form action="/creategroup/" method="post" id="post-form"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-4 mb-0"> {{ form.group_name|as_crispy_field }} {{ form.group_location|as_crispy_field }} </div> </div> <button type="submit" class="btn btn-primary">Create Group</button> </form> </div> {% endblock %} -
How to create a DRF API to return all possible field choices available along with User list as dict
I am creating an API using DRF, and I want to send a JSONResponse which will contain a list of all users (from django User model) and available choices for few fields as a dict. I tried to create a GenericAPIView with queryset of all active users and in serializer I tried to return the field choices and list of users but the result contains field options along with each user object. I want to keep all users data under key "user_list" and field options under "field1_choices", "field2_choices". GenericAPIView: class TicketPropertiesView(generics.GenericAPIView): authentication_classes = [ CsrfExemptSessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] serializer_class = TicketPropertiesSerializer def get(self, *args, **kwargs): serializer = TicketPropertiesSerializer(data = User.objects.filter(is_active = True), many = True) serializer.is_valid() return JsonResponse(serializer.data, safe = False) Serializer: class UserPropertiesSerializer(serializers.ModelSerializer): user_list = serializers.SerializerMethodField() field_1_choices = serializers.SerializerMethodField() field_2_choices = serializers.SerializerMethodField() FIELD_1_MAP = FIELD_1_CHOICES FIELD_2_MAP = FIELD_2_CHOICES def get_user_list(self, obj): queryset = User.objects.filter(is_active = True) user = [] for obj in queryset: user.append({ "id": obj.id, "username": obj.username, "first_name": obj.first_name }) return user def get_field_1_choices(self, *args): field1_choices = [] for i in self.FIELD_1_MAP: field1_choices.append({"id": i[0], "choice": i[1]}) return field1_choices def get_field_2_choices(self, *args): field2_choices = [] for i in self.FIELD_2_MAP: field2_choices.append({"id": i[0], "choice": i[1]}) return field2_choices class Meta: model β¦ -
Django ChromeDriver Disable Downloads
I am using Selenium and ChromeDriver in a Django application. When I navigate to a particular page it downloads a file(that I don't want). When the browser runs with the head it saves files to my downloads folder. When it runs headless it downloads files to the project folder(same level as manage.py). I want to navigate to the page, but not make any downloads. I looked at the documentation: https://cs.chromium.org/chromium/src/chrome/common/pref_names.cc?l=38 https://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/pref_names.cc?view=markup And a handful of posts on SO. It's still downloading the file. How do I stop it? Is this a chromedriver issue or a Django issue? scrape.py options = webdriver.ChromeOptions() options.add_argument('headless') driver = webdriver.Chrome(options=options) prefs = {"profile.default_content_settings.popups": 2, "download_restrictions": 3, "profile.default_content_setting_values.automatic_downloads": 1, "safebrowsing.enabled" : True } options.add_experimental_option("prefs", prefs) -
is there a way to save current data on another page using django?
I want to allow users to save an email on another page of my web app. for example when the user finds the email that he is looking for. he will click add to lead, and that the same email is going to be added on the leads page. I try but still can't figure it out, thanks guys in advance. url.py url(r'^lead/$', views.lead, name='lead'), what I want is that as soon as the user clicks this link, the email is going to be saved in the leads page. app index.html <a href="/app/lead" title="add lead" > views.py def lead(request): new_item=Blogger(email = request.POST["email"]) new_item.save() return render('app/leads.html',{'new_item':new_item}) -
Calling a django APi in React shopping Cart
I have built a react shopping Cart application which has a login page Signup Page Products Add to Cart and other features like Checkout through Api . Now the other person from my team has build a backend api on django. I want to call that api from my react code now. How should I do it? Do I need to learn something specific? I have searched in internet and all of the sources we to make serve react and django from same project. I have a React project with me and a separate api developed by someone else. Please guide me through this. -
How to make separate database for every user in Django?
So I am new in programming in general and I am currently learning Django. I know it may be a stupid question, but I don't seem to find the answer anywhere and I really want to know it. I am making a basketball stats tracker app. How this works is you enter how many times you scored out of how many attempts and it adds it to your current accuracy percentage. Let's say last time you were 5/10 and now you are 35/90. Then the percentage goes from 50% to 40%. It works for me but I want to make it so people can sign up. I know how to do that but how do I make the stats personalized for every user? -
Many-to-Many Signals
I'm trying to use django signals to prevent many-to-many orphans from forming in my project. Consider the following models: class Attachment(models.Model): some_field = models.FileField() class ModelA(models.Model): attachments = models.ManyToManyField(Attachment) class ModelB(models.Model): attachments = models.ManyToManyField(Attachment) def attachment_relation_changed(sender, **kwargs): action = kwargs.get('action') if action == 'post_remove': ids = kwargs.get('pk_set') Attachment.objects.filter(id__in=ids).filter(modela=None).filter(modelb=None).delete() This properly deletes orphaned Attachment instances when using attachments.set() or attachments.remove() on ModelA or ModelB but doesn't handle ModelA.delete(). Do I need to manually send these signals by overriding the delete functions on ModelA and ModelB? Also, is there a way to do something along the lines of this: Attachment.objects.filter(relations=None).delete() in case any new models are registered with a m2m attachments fields? -
How to get a Permalink to a CSS when using Django-Compressor and Offline Compression
I'm using Django-Compressor with Offline Compression and I need to get a permalink to the compressed css file. {% compress css %} <link rel="stylesheet" type="text/x-scss" href="{% static 'styles/sass/main.scss' %}" /> {% endcompress %} I'm getting a file similar to this on each deploy: /static/CACHE/css/main.175851321d0a.css for the website usage it's fine but I also need to link to that css from an external tool so I need to have kind of a permalink to that file kind of: /static/CACHE/css/main-permalink.css A CSS filename that doesn't change on every deploy Is there a way to do that? Thanks in advance. -
Can I detect text input change (in form) without POST action in Django?
I have Model form with charfield of username. I want to get value of field after user stopped entering text to use it in my python code in view. How can I achieve that with Javascript? Is it possible to do it without JS? -
'ImageFileDescriptor' object has no attribute 'objects'
I'm trying to iterate through the images in my categories but I'm getting 'ImageFileDescriptor' object has no attribute 'objects' models.py class Category(models.Model): category_title = models.CharField(max_length=200) category_image = models.ImageField(upload_to="category") category_description = models.TextField() slug = models.SlugField(max_length=200, unique=True, default=1) def get_image_path(self, filename): gallery_path = os.path.abspath( os.path.join(settings.MEDIA_ROOT, self.slug)) if not os.path.isdir(gallery_path): os.mkdir(gallery_path) return os.path.join(gallery_path, filename) gallery = models.ImageField(upload_to=get_image_path) def create_directory(self): gallery_path = os.path.abspath( os.path.join(settings.MEDIA_ROOT, self.slug)) if not os.path.isdir(gallery_path): os.mkdir(gallery_path) def save(self, *args, **kwargs): if not self.pk: self.create_directory() super().save(*args, **kwargs) def delete(self, *args, **kwargs): shutil.rmtree(os.path.join(settings.MEDIA_ROOT, self.slug)) # os.rmdir(os.path.join(settings.MEDIA_ROOT, self.slug)) super().delete(*args, **kwargs) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.category_title views.py def category_detail_view(request, slug): category = get_object_or_404(Category, slug=slug) context = { "gallery": Category.gallery.objects.all(), } return render(request, 'main/category_detail.html', context) category_detail.html {% for image in gallery %} <div class="col-md-4"> <a href="{{ image.url }}"> <img src="{{ image.url }}" class="img-responsive img-thumbnail" width="304" height="236"/> </a> </div> {% endfor %} For some reason creating galleries in Django has been difficult for me. It seems as if there is no standard way that most people are doing this. Even if I get this to work, I don't see how one could manage the uploaded images from the admin panel. ex upload delete arrange etc If you could shed some light on this β¦ -
How to pass instance primary key from HTML to views.py?
I have a table of model instances as following: _____________________ |1| | | |<a/>| _____________________ |2| | | |<a/>| _____________________ |3| | | |<a/>| ....................... _____________________ Django generates it with for template loop an the first column is a primary key of model instance. The last column is a link to the page fith form to edit this model instance. I have 2 functions in views.py: to render this page (edit_employee()) and to submit changes (edit_employee_action()). In the last one I need to process this primary key. How can I pass the primary key from HTML to views.py? How can I pass this key from edit_employee() to edit_employee_action()? I could create global variable, but this is not the best way I suppose.