Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django add multiple pictures/files to existing model to foreinkey
Im trying to add multiple pictures to a model and connect it to existing model with foreign key. First my code snippets urlpatterns = [ url(r'^$', views.MemoriesIndexListView.as_view(), name='index'), url(r'^add-attachment/(?P<question_id>\d+)/$', views.UploadView.as_view(), name='attachment'), ### some more urls ### ] models class Question(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='remember_user') ### some more fields ### class Attachment(models.Model): question = models.ForeignKey(Memories, on_delete=models.CASCADE) file = models.FileField(upload_to='attachments') views class UploadView(FormView): template_name = 'remember/attachment_form.html' form_class = UploadForm def form_valid(self, form): for each in form.cleaned_data['attachments']: Attachment.objects.create(file=each) return super(UploadView, self).form_valid(form) def get_success_url(self): return reverse("remember:index") forms class UploadForm(forms.Form): attachments = MultiFileField(min_num=1, max_num=10, max_file_size=1024*1024*5) But, when I try to migrate, I ge t this error: You are trying to change the nullable field 'question' on attachment to non-nullable without a default; we can't do that (the database needs something to populate existing rows). I tried to add default=1, but then is the saved primary key always 1. How can I add the correct PK which is connected with the model Question to the Attachment? -
CSS not working with all templates in Django Web App
I am new to Django Web Development and am building my first web app. Need your help on one of the points I am stuck. So I ave created views, templates and a static directory to store my css files. The css styling works perfectly fine with my home.html template but for some reason when I try using the same css files for my other linked pages on the same sight, it doesn't have any effect on the page. The page remains the way it is with its basic formatting. Any help would be appreciated. I have tried using the same style.css file connected to the home.html for another page on the website like team.html but it doesn't work. Home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script> <link rel="stylesheet" href="https://m.w3newbie.com/you-tube.css"> {% load static %} <link href="{% static '/css/style.css' %}" rel="stylesheet" type="text/css"> </head> <body> {% include "main/includes/home_navbar.html" %} {% include "main/includes/image_slider.html" %} {% include "main/includes/jumbotron.html" %} {% include "main/includes/welcome_section.html" %} {% include "main/includes/home_team_section.html" %} {% include "main/includes/philosophy.html" %} {% include "main/includes/connect.html" %} {% include "main/includes/footer.html" %} <div class="container"> <br> {% block content %} {% endblock … -
"ImportError: Couldn't import Django." even after installing Django within Virtualenv
I'm a newbie in Python, and I'm just getting into Django tutorials. I get the concept of creating a virtual environment, installing Django in it and then setting up my project structure alongside it. But then, I must have messed something up, because my "python manage.py migrate" command returns an error that it can't find a module named Django, despite the fact that I had just installed Django. Here's what I did: PS D:\f drive\KK\Projects\Git\python\Dev> virtualenv kk_env Using base prefix 'c:\\program files\\python37' New python executable in D:\f drive\KK\Projects\Git\python\Dev\kk_env\Scripts\python.exe Installing setuptools, pip, wheel... done. PS D:\f drive\KK\Projects\Git\python\Dev> pipenv --python 3.7 install django==2.2 Virtualenv already exists! Removing existing virtualenv… Creating a virtualenv for this project… Pipfile: D:\f drive\KK\Projects\Git\python\Dev\Pipfile Using C:/Python/Python37-32/python.exe (3.7.4) to create virtualenv… [= ] Creating virtual environment...Already using interpreter C:\Python\Python37-32\python.exe Using base prefix 'C:\\Python\\Python37-32' New python executable in C:\Users\karthik\.virtualenvs\Dev-g5SlP1CQ\Scripts\python.exe Installing setuptools, pip, wheel... done. Running virtualenv with interpreter C:/Python/Python37-32/python.exe Successfully created virtual environment! Virtualenv location: C:\Users\karthik\.virtualenvs\Dev-g5SlP1CQ Creating a Pipfile for this project… Installing django==2.2… Adding django to Pipfile's [packages]… Installation Succeeded Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… Success! Updated Pipfile.lock (f002eb)! Installing dependencies from Pipfile.lock (f002eb)… ================================ 3/3 - 00:00:01 To activate this project's virtualenv, run … -
Reverse queryset/list, then slice
I have a Django queryset, which in simpler terms seems to be an extension of lists (Please correct me if I'm wrong) I need to: Reverse the queryset or list, and then Slice the list I was doing it in the form of: return reversed(querySet)[:20] However, now for some reason I am getting the error of: "'reversed' object is not subscriptable" I could easily do: return querySet[:20:-1] but this causes the list to be sliced first, then ordered backwards. Thus I am in the process of finding the next best hacky way to achieve this; but while I find it, I was wondering what your best approach is? -
id is not present in validate() and ListSerializer's update() Django Rest Framework
I'm learning and new to Django Rest Framework and I'm having an issue in serializer validations and ListSerializer update method. I have an APIView class which handles the put request. I just wanted to have a custom validation and so I've overridden validate method in the serializer class. From postman I'm sending a JSON data to this APIView Class. Sample JASON data: [ { "id": 1, "ip": "10.1.1.1", "host_name": "hostname 1" }, { "id": 2, "ip": "10.1.1.2", "host_name": "hostname 2" } ] When I receive the data and do serializer.is_valid() it passes the flow to the overridden validate function. But in there when I check for the attrs argument, I get all the fields except the id. The key and value for id are not present. It shows None. The same issue occurred to me when I was trying to override the update method in ListSerializer. when I tried the below code in the ListSerializer's update method, data_mapping = {item['id']: item for item in validated_data} I got an error saying KeyError 'id'. It seems it's not accepting id field and I'm not sure why! Please, someone explain this to me if I'm wrong anywhere. -
Update complex dict with another dict with different formatting
I have two python2 dictionaries and I want to run dict1.update(dict2). Unfortunately right now I am getting the error: ValueError: dictionary update sequence element #0 has length 1; 2 is required When I try doing that. Now I need a way to transform first or the second dictionary to make the update successful. First dictionary looks like this: {'xpos': 1000012783L, 'tags': [{'searchParameters': None, 'category': u'C Discovery Tags', 'tagGuid': u'VT0000068_112783_f000819_sf063'}], 'functionalData': [], 'notes': [], 'selectedMainTranscriptId': None, 'alt': u'A', 'guid': u'SV0000023_112783_f000819_sf063', 'ref': u'G', 'id': 23} Second looks like that (It is actually retrieved from JSONField from a Django model): {"liftedOverGenomeVersion": null, "pos": 12783, "predictions": {"splice_ai": null, "eigen": 0.299, "revel": null, "mut_taster": null, "fathmm": null, "phastcons_100_vert": null, "polyphen": null, "dann": 0.2757730705502398, "sift": null, "cadd": 0.828, "metasvm": null, "primate_ai": null, "gerp_rs": null, "mpc": null}, "clinvar": {"alleleId": null, "clinicalSignificance": null, "variationId": null, ...} I verified the types of the dictionaries, and they are both <type 'dict'>. Any suggestions would be greatly appreciated -
Django custom ModelField - getting a "attribute name must be string" error
So I created a custom ModelField extending CharField to have better empty string validation and to allow me to run custom business logic validation and cleaning on it. The code is below: class CustomTextField(models.CharField): 10 def __init__(self, *args, rule="TextRule", **kwargs): 11 self.rule = rule 12 super().__init__(args, kwargs) 13 14 def deconstruct(self): 15 name, path, args, kwargs = super().deconstruct() 16 # Only include kwarg if it's not the default 17 if self.rule != "TextRule": 18 kwargs['rule'] = self.rule 19 return name, path, args, kwargs 20 21 def validate(self, value, model_instance): 22 super().validate(value, model_instance) 23 # skip special cases here 24 if self.blank and self.rule == TextRule: 25 return 26 rule_module = __import__("webapp.rules", fromlist=['blah']) 27 class_ = getattr(rule_module, self.rule) 28 rule = class_(value) 29 result = rule.validate() 30 if result != "": 31 raise ValidationError(result) 32 33 def clean(self, value, model_instance): 34 value = super().clean(value, model_instance) 35 rule_module = __import__("webapp.rules", fromlist=['blah']) 36 class_ = getattr(rule_module, self.rule) 37 rule = class_(value) 38 return rule.clean() So the idea is, it's basically a CharField that runs my TextRule object by default, but can be overriden to run other text type rules (e.g. Phone number, email, etc), to do custom validation and cleaning of data. But … -
django-axes is not getting the request argument
I recently added django-axes to my django project and it is suppose to work out the box with django-restframework, however I am using django-rest-framework-simplejwt to handle authentication, but it should still work out the box since the only thing that is required for django-axes is passing Django's authentication method the request object which it does in it's source code(line 39 and 43). When I try to authenticate, I get this error from django-axes: axes.exceptions.AxesBackendRequestParameterRequired: AxesBackend requires a request as an argument to authenticate -
Can Django template tags be used like Django Template callables?
I'm using the the Django Template Language to call into a model's method to create dynamic ids according to product-specific logic. JSON files hold product-specific configuration information. I use the Django Template Language in strings in the JSON files so each product has their own logic for creating product-specific ids. It works great with a Django Template Language callables. The id_template has a callable to the to a model's method get_next_policy_id: { "model": "some name", "product_id": "some product name", "id_template": "{{ product.get_next_product_id }}" } Here's the relevant code from the product model. You can see the method that provides the id, and the save method conditionally uses it. class Policy(): [...] def get_next_policy_id_risk_strategies(self): policy_num = -1 sequence_name = self.product.product_id + '-' + self.source_application.form["state"] if self.source_application.form["state"] == "NY": policy_num = get_next_value(sequence_name, initial_value=200_000) elif self.source_application.form["state"] == "IA": policy_num = get_next_value(sequence_name, initial_value=400_000) else: sequence_name = self.product.product_id policy_num = get_next_value(sequence_name, initial_value=300_000) policy_id = self.product.product_id + "-" + str(policy_num) return policy_id That works great. However, I'd like to have no product-specific code in the model. I could do this almost entirely in the Django Template Language, but the requirements for the product id, is they vary by state sequentially. So, get_next_value draws from a persisted … -
In Django, how to use settings.py constant from a static file?
I have a static file that I use in my template. I need to hide some information in this file code but I normally use settings.py constants to do that. How can I instance a settings.py constant in a static file? I tried {{CONSTANT}} but iit doesn't work. -
Django how to call a method from a custom field given a model instance?
I have the following model: class CustomField(models.CharField): def foo(self): return 'foo' class Test(models.Model): col1 = models.CharField(max_length=45) col2 = CustomField(max_length=45) How can I call the foo method from CustomField, if I'm given an instance of Test? For example: >>> Test.objects.create(col1='bar', col2='blah') >>> t.col2 'blah' >>> t.col2.foo() 'foo' This, of course, throws: 'str' object has not attribute 'foo' because calling model_instance.column returns the value of that column, not an instance of column. But why exactly? It seems Django's ORM magically transforms an instance of a field class into a value. I've spent hours digging through source code and can't seem to find where the transformation takes place. TLDR; Is it possible to return an instance of a field class given a model instance? Any idea where this happens in Django's source code? I assume this takes place in django/db/models/base.py, but that file is over 1800 lines of code, so it's really hard to tell. -
How to use a live server when developing angular/django locally
After using Angular 8 & Node.js, I've grown to enjoy developing locally with hot reloading on both the backend and frontend. Now I'm trying to use Django for a backend and I'm struggling with a way to hot reload the entire app without having to build the angular project into the django template. It seems like it will be extremely time consuming to build out the frontend every time I want to see changes. Is there a way to develop while running a local server for both django and angular to view the changes in real time? This is the example I followed to set up the project, but it requires you to run 'ng build' to grab and place the JS files in django's folder in order to view the full-stack app. https://devarea.com/building-a-web-app-with-angular-django-and-django-rest/#.XYz-JEZKhPZ In Node.js, I can run nodemon while serving the angular app on localhost. Both have hot reloading. If this could be replicated in django/angular that'd be fantastic. Thanks in advance! -
Django: How can I use variable defined in the other .py file?
I would like to use below x as variable in function get_price() in the other file plots.py. views.py class ScatterView(TemplateView) : def get(self, request, *args, **kwargs) : context = super().get_context_data(**kwargs) context['form'] = SampleForm() x = request.GET.get('x') context['calculated_x'] = plots.get_price() return render(request, 'index.html', context) plot.py def get_price(): input_x = x + 1 return input_x But it doesn't work. How shall I describe the function for this purpose? The point is, I need to use the returned value for template later via views.py. -
Submit text field in Django template with js-upload-photos button
I have Django app to upload photos, following the great example at Simple Is Better Than Complex. That part works fine. I would like to add a feature that allows a user to type in text that will be applied to all the photos they upload (which is a field in the model). I tried just adding {{ form.as_p }} in the template form, but that just created a separate form with a separate button. Next, I added a text input field to the template, but nothing seems to happen with that since the button is type=button rather than submit. Then I tried adding some jquery/javascript to submit that text field, but that returned an error Forbidden (CSRF token missing or incorrect.). Can anyone tell me how to efficiently and correctly submit a text field to a Django view with this type of button? Or is there a good solution for the CSRF token error? Relevant pieces of code below. <!-- images_upload.html --> {% extends "base_generic.html" %} {% load staticfiles %} {% block content %} {% block javascript %} <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script> <script … -
Django and Kuberentes, Do we encapsulate the source code inside the docker image?
Let's assume that we have a Django web application. If we want to move from docker-compose to Kubernetes, do we need to copy the source code into the docker image, or we could mount the source code via a volume to pods. I'm thinking with multi-web pod replicas scenario when I want to push new features to deployment on Kubernetes, How Kubernetes will take care of turning off old pods with their old source code and turning on new pods with the new changes. My question is, I just need some clarification about the whole process and how it differs from docker-compose. In docker-compose, I would stop all containers, git pull new changes from remote, build the images and then docker-compose up. In contrast, in Kubernetes what is going to happen? is it just from a CI/CD server where it would build the docker images and push them to some registry of interest and only then we could ssh to the prod server and just use Kubectl API to roll out the updates, consequentially it would just need to pull the docker images? Am I missing something from the above hypothetical scenario? My concern of this approach is that by … -
How to validate form if empty values passed to form fields in Django?
Below is the form: struggling to validate form with sending empty values for some form fields. Name and phone were mandatory field. When user type and click submit, All the values should be concatenated and save it in file. forms.py from django import forms class ReviewForm1(forms.Form): PRECAUTIONS_CHOICES = ( ('no', 'No'), ('yes', 'Yes') ) UNIT1_CHOICES = ( ('Very Satisfied', 'Very Satisfied'), ('Satisfied', 'Satisfied'), ('neutral', 'neutral'), ('Unsatisfied', 'Unsatisfied'), ('Very Unsatisfied', 'Very Unsatisfied'), ) name = forms.CharField(required=True, widget=forms.TextInput(attrs={'required': 'true'})) phone = forms.CharField(required=False) email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'required': 'true'})) precautions = forms.ChoiceField(required=True, choices= PRECAUTIONS_CHOICES, widget=forms.Select()) unit1_ambience = forms.ChoiceField(required=True, choices= UNIT1_CHOICES, widget=forms.Select()) review = forms.CharField(required=False, widget=forms.Textarea()) def clean(self): name = self.cleaned_data.get('name') phone = self.cleaned_data.get('phone') review = self.cleaned_data.get('review') email = self.cleaned_data.get('email') precautions = self.cleaned_data.get('precautions') unit1_ambience = self.cleaned_data.get('unit1_ambience') expected_string = '' options = [name,phone,review,email,precautions,unit1_ambience] for option in options: if not option: continue else: expected_string = expected_string + option + '\n' # concat all with review and then return string return expected_string views.py snippet @require_POST @csrf_protect def revfile_save(request): """ This page processes and saves review file. """ form = ReviewForm1(request.POST) if form.is_valid(): review = form.cleaned_data reviewfile_name = "/root/sjfacweb/" + remote.sjfacweb() #content writes to timestamped filename remote.write_reviewfile(reviewfile_name,False,review) Below is the error I am getting when clicked save: local variable … -
Is there a way to get from the model and display the count of images per advert that a user posted
I'm trying to get the total count of images per each advert that was posted by a user. I want to display this count on my template. I have tried several solutions online to see if I could get this to work but I have kind of hit a brick wall. It's something I see on e-commerce sites; so I know it is possible. Please help... My Model class Advert(models.Model): """All adverts""" STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=49) description = models.TextField() price = models.PositiveIntegerField() date_created = models.DateTimeField(auto_now_add=True) date_posted = models.DateTimeField(auto_now=True) state = models.ForeignKey(State, on_delete=models.DO_NOTHING) city = models.CharField(max_length=255, blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') image_primary = models.ImageField( upload_to="product_pictures", verbose_name='Image (required)') image_2 = models.ImageField( upload_to="product_pictures", blank=True, null=True) image_3 = models.ImageField( upload_to="product_pictures", blank=True, null=True) image_4 = models.ImageField( upload_to="product_pictures", blank=True, null=True) image_5 = models.ImageField( upload_to="product_pictures", blank=True, null=True, default=None) class Meta: ordering = ['-id'] def __str__(self): return self.title my View def view_all(request): """View All view""" view_all_list = Advert.objects.all().order_by('date_posted') context = { "view_all_list": view_all_list } return render(request, 'view-all.html', context) my template {% for items in view_all_list %} <a href="" class="col card-sm"> <div class=" row"> <span class="numbertext"><i style="margin-right: 4px;" class="fas fa-camera"></i>{{items.****}}</span> <img … -
How to make a username as a foreign key of another model in django
I am very new to Django. Actually the story is that I want to linked a model which has 2 field 'username' and 'password' I wann'a make 'username' field as as Foreign in another model. But as per Django we can only pass the whole Model Object who is referring to as it's foreign key. So kindly guide me if I am wrong somewhere and please give me any solution regarding this basic problem I know. -
GitHub Folder Data Storage
In what structure does GitHub store folder data in their database? I am creating a git webhook on my local git server and am trying to store the folder data efficiently. Thanks in advance. -
Django Rest Framework - Translating external unique code to a internal id and vice versa
I am building a Rest Api that read and update a model called Requirements. I am using a ModelSerializer. The Requirements model has a foreign key on the Materials model. The problem is that my api user does not know the internal id of Materials He knows only a code that is unique for the material. Now, the idea is that in PUT he passes me the material_code and I set the material id and in GET he receives the material code based on the material foreign key of Requirements I managed to make PUT to work by overriding the validate method and declaring: material_code = serializers.CharField(max_length=50); This is the code supplied in the end of the post. Notice, please, that this is a snippet of the complete code that is much complex. In the complete code the Requirements serializer is nested inside another serializer that is nested is nested inside another serializer. But I do not think this is relevant to the problem. Then I manage to make GET to work by the use of a custom source option in material_code field where the source is a property on my Requirements model. For this the declaration must be changed … -
Trouble in Writing Django Rest Api Permission class for a updateview
I am going through trouble in writing a permission class for a updateView. I am using custom user model that extends with AbastractBaseUser this is my models: class Person(models.Model): person_choice = [ ('MA', 'MESS ADMIN'), ('MM', 'MESS MEMBER'), ] auth_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_auth') name = models.CharField(max_length=50) person_type = models.CharField(choices=person_choice, max_length=50) mess = models.OneToOneField('mess.Mess', on_delete=models.PROTECT, null=True, blank=True, related_name='person_mess') class Mess(models.Model): name = models.CharField(max_length=50, null=False, blank=False) address = models.CharField(max_length=300) admin = models.OneToOneField(Person, on_delete=models.CASCADE, related_name='mess_admin') members = models.ManyToManyField(Person, related_name='mess_members') and this is my View for Mess class AddMessMemberView(UpdateAPIView): serializer_class = MessSerializers permission_classes = () queryset = Mess.objects.all() lookup_field = 'pk' I want to implement in this updateView a MESS ADMIN of a mess can update Mess model but a MESS MEMBER cant update this mess model. I guess i need to write a Permission Class for view but i am not getting how to write a permission class for this view. Can anyone help me in this case? -
Django Multiuser with separet model instance
I want to create a multiuser app using django for example note taking app Where after registration each user will get an individual panel and no one can see other users created notes but user can create staff user and give him permission to edit his notes. What's the process? Please help me -
Getting an error when redirecting to an url after object creation in Django
I am getting the below error message when going to create an object with generic "CreateView" function. "Reverse for 'detail' with arguments '()' and keyword arguments '{'pk': 4}' not found. 0 pattern(s) tried: []" # view function class AlbumCreate(CreateView): model = Album fields = ['album_title', 'artist', 'genre', 'album_logo'] # Model class Album(models.Model): album_title = models.CharField(max_length=250) artist = models.CharField(max_length=250) genre = models.CharField(max_length=100) album_logo = models.ImageField(upload_to='Image') def get_absolute_url(self): return reverse('music:detail', kwargs={'pk': self.pk}) def __str__(self): return self.album_title + '-' + self.artist -
How to hide js libraries used in my Django app
I have been researching on web security and discovered that it is possible to detect the js libraries used on your site and allow a hacker to use that information to use a specific attack. I can't find any way of hiding that information in my Django app when using penetrating testing tools -
intermittent django middleware process_request skipped?
this is intermittent which may mean there is a race condition or something ... unfortunately i doubt this will be easily reproducible class StopWatch: def process_request(self,request): request.start_time = time.time() def process_response(self,request,response): total_time = time.time() - request.start_time Occasionally (quite infrequently) request.start_time will give attribute error ... I dont understand the path that django takes where process_response is called, but process_request is not originally I was storing the start time at the instance level (but then it would regularly report very short render times, leading me to believe that a single instance is shared among threads (and so i removed self.start_time in favor of request.start_time)