Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix 'This field is required' while submitting Django's ModelForm?
I'm using data from .csv file to prepopulate ModelForm choises. But the problem is that after clicking submit all required fields of ArticleForm and ArticleTranslationForm throw an error This field is required. Let me explain how It should work: I need a simple django-app which will allows user to load table data from file to be feed as choices parameter for each form field. After clicking 'Submit' the row data will be serialized in JSON file, otherwise the data from next row should be past in choices and form should be "refreshed". models.py class Article(models.Model): identifier = models.CharField(unique=True, max_length=255) number = models.CharField(max_length=255) ... collection = models.CharField(max_length=255) verified = models.IntegerField() class Meta: abstract = True class ArticleTranslation(models.Model): name = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) ... lightproofness = models.CharField(max_length=255, blank=True, null=True) kind_of_removal = models.CharField(max_length=255, blank=True, null=True) class Meta: abstract = True forms.py class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['identifier', 'number', ..., 'collection', 'verified'] class ArticleTranslationForm(forms.ModelForm): class Meta: model = ArticleTranslation fields = ['name', 'description', ..., 'lightproofness', 'kind_of_removal'] views.py def mapper(request): data = read_file(path='export_full.csv') if request.method == 'POST': article_form = ArticleForm(request.POST) translation_form = ArticleTranslationForm(request.POST) if article_form.is_valid() and translation_form.is_valid(): pass # does nothing, just trigger the validation else: article_form … -
How can I use a generator of JPEG images and convert it into a video stream?
I'm trying to setup a website to access a security camera from the outside world. However, it only has one image per refresh, and it's a JPEG. However, I'm not sure what the best approach is. I've tried taking the JPEG and putting it into a generator, and then passing that into StreamingHttpResponse. However on mobile it stops after a while, and I don't know how to easily apply HTML/CSS to it to make it look nice. The code below is my StreamingHttpResponse solution, but again, it doesn't work too well. def content_gen(url): while True: res = requests.get("{}/top.htm".format(url), allow_redirects=True) soup = BeautifulSoup(res.content, 'html.parser') image = "{}/{}".format( url, soup.html.body.table.find_all('tr')[4].td.table.tr.img['src'] ) byte_resp = requests.get(image) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + byte_resp.content + b'\r\n\r\n') I'm not exactly sure what to do, I don't know how to integrate AJAX with this which is what I've seen suggested. If possible, I'd like to see an example just to see it materialized better. -
Mousewheel scroll on iframe does not work when file served via Django
Please have a look here for more details: https://youtu.be/CLzQU-5iNIA I create a simple html file with a bunch of iframe videos from youtube. I save the file and open it in chrome. I move the cursor over the videos and use the mousewheel to scroll. It works! Now, I serve the exact same file via Django using Runserver. I move cursor over video and use the mousewheel to scroll. It does NOT work! Chrome Version 71.0.3578.98 (Official Build) (64-bit) -
Unable to create object from form
After changing the field used as the primary key in a model, I now receive an error when trying to create an object from a form. I have deleted everything in the migrations directory and performed makemigrations and migrate. I do not believe the problem is with the database, rather something in the code no longer functions the same now that I am not using a custom primary key. As someone new to Django, I suspect I am missing something fundamental but cannot quite identify what that is. views.py @login_required def job_create(request): client = request.POST.get('client') form = JobForm(request.POST or None) form.fields['client'].initial = Client.objects.get(client_name=client) if request.method == "POST": if form.is_valid(): form.save() return JsonResponse({"Success": True})` models.py class Client(models.Model): client_name = models.CharField(max_length=255, unique=True) def __str__(self): return self.client_name class Job(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) job_number = models.CharField(validators=[RegexValidator(regex='^\d{4}$', message='Invalid job number', code='invalid')], max_length=4, unique=True) job_description = models.CharField(max_length=30) forms.py class JobForm(forms.ModelForm): class Meta: model = Job fields = ('client', 'job_number', 'job_description',) The above code fails to create and save the object into the database. Below is my attempt to recreate this using the Django shell: >>> from myproject.models import Client, Job >>> from myproject.forms import JobForm >>> client = Client.objects.get(client_name='John') >>> jobform = JobForm() >>> jobform.client … -
Combing Django/HTML & Javascript
I have the following block of code in my Django project, HTML view: {% for world in world_list%} {% if forloop.first %}<div class="row">{% endif %} <div class="col-xs-4 center-block"> {% if world.cover_image %} <img src="{{ world.cover_image.url }}"> {%endif%} <h2 href="#"> {{ world.name }} </h2> </div> {% if forloop.counter|divisibleby:3 %}</div><div class="row">{% endif %} {% if forloop.last %}</div>{% endif %} This displays a set of data in bootstrap row/columns depending on how much data there is. What I would like to do is centre the images as they are rendered in the middle of the columns. I looked at this stackoverflow answer and it recommends a jQuery plugin, specifically this one. The example shown in the github is: $('ul.image-list img').centerImage(); but what I don't understand is how I can apply the .centerImage() function call to this line of code in my module: <img src="{{ world.cover_image.url }}"> I am new to the world of the web so if I'm missing something obvious please tell me. -
SQL Alchemy not handling single quotes in column name
For multi-index dataframes, Pandas writes the column names to the database in the format ('index1[i]', 'index2[i]'). When trying to save to the DB this results in the following error: KeyError at .../ "('SF', 'monkeys'" Where SF is the first index and monkeys is the second. The closing parens is truncated. I've tried to trace this all through the stack and I can confirm Pandas is generating the following statement: CREATE TABLE "data" ( "('SF', 'monkeys')" REAL, "('SF', 'orangutans')" REAL, "('SF', 'girafes')" REAL, "('LA', 'monkeys')" REAL, "('LA', 'orangutans')" REAL, "('LA', 'girafes')" REAL ) But it doesn't seem to be working with SQL Alchemy Pandas code: dataframe.to_sql( '"{}"'.format(self._table_name), index=False, chunksize=50000, con=engine, ) SQLAlchemy engine engine = sqlalchemy.create_engine( "postgresql://{}:{}@{}:{}/{}".format( _warehouse_db_settings["USER"], _warehouse_db_settings["PASSWORD"], _warehouse_db_settings["HOST"], _warehouse_db_settings["PORT"], _warehouse_db_settings["NAME"], ) ) -
Simple Django rest framework Authentification
I'm building a Django API, with the Django Rest Framework, and Angular 7 for the front app. I'm lookng for a simple way to just test if an user is authentified or not, but I can't find it. Is there a way to use easily the Django default Authentification system (I'm user the Django AbstractUser) Thank you. -
Post params are showing in request.body instead of request.POST
this is actually a javascript question. When I'm submitting the form my Django server shows the params only in request.body. What am I doing wrong? thanks! -
Google Cloud SQL - Django - PostgreSQL Backups and Restorations
I am in the process of creating a database backup portion of my Django project I have opted to use dumpdata per my question here: Django Dumpdata with Specific DB and I have stored the output of the dumped data into a DB table stored in my project's only DB instance on Google App Engine. My question, since Google only provides full instance backups and I am storing client DB and universal DB backups in my default DB with the dumpdata command through my project's only DB instance, what is the proper method of restoring data if my actual main Gcloud DB instance needs to be restored before I can access my individual entries that hold the dumpdata information? Would it be best for me to create a separate instance for DB backups, or would it be best to restore the instance to a new instance, grab the dumpdata entries for each client DB, and then run loaddata for them? I've tried to be brief as this is a logistics question, if you need more information to show what I am describing, I can certainly provide it. I am looking for suggestions from users who have also used the Google … -
Implementing Freshsales API in Python
I am trying to integrate Freshsales functionality within my Django server in order to create leads, schedule appointments, etc. Freshsale's API Documentation in Python lacks detail, however. Here is a link to their API functionality using curl commands: https://www.freshsales.io/api/. Their python code is as follows: from .freshsales_exception import FreshsalesException import requests import json def _request(path, payload): try: data = json.dumps(payload) headers = { 'content-type': 'application/json', 'accept': 'application/json' } resp = requests.post(path, data=data, headers=headers) if resp.status_code != 200: raise FreshsalesException("Freshsales responded with the status code of %s" % str(resp.status_code)) except requests.exceptions.RequestException as e: raise FreshsalesException(e.message) In the case of the curl command, for example, to create an appointment, is: curl -H "Authorization: Token token=sfg999666t673t7t82" -H "Content-Type: application/json" -d '{"appointment":{"title":"Sample Appointment","description":"This is just a sample Appointment.","from_date":"Mon Jun 20 2016 10:30:00 GMT+0530 (IST)","end_date":"Mon Jun 20 2016 11:30:00 GMT+0530 (IST)","time_zone":"Chennai","location":"Chennai, TN, India","targetable_id":"115765","targetable_type":"Lead", "appointment_attendees_attributes":[{ "attendee_type":"FdMultitenant::User","attendee_id":"223"},{"attendee_type":"FdMultitenant::User","attendee_id":"222"},{"attendee_type":"Lead","attendee_id":"115773"}] }}' -X POST I understand that I need to use the requests library to make a post request. However, I do not understand how I need to format the request. The furthest extent I understand to list all appointments, for example, is for my request to be the following: my_request = "https://mydomain.freshsales.io/api/appointments/token=myexampletoken" response = requests.post(myrequest) I am unsure of how … -
Django forloop on Queryset returning same user
I have created a queryset in Django to filter by location. 1) If a location is not typed in, the page should display all users. 2) If a location is typed in and it matches another user, only that user should be shown. I am running a forloop on the queryset to populate the page with users which match the filter. Right now, the page is returning the same user twice and not showing any of the other users. Here is an image. Would anybody be able to diagnose what is going wrong? I have omitted code that is not relevant. filters.py import django_filters from .models import Profile class ProfileFilter(django_filters.FilterSet): class Meta: model = Profile fields = { 'city': ['iexact'], } views.py @login_required def profile_filter(request): f = ProfileFilter(request.GET, queryset=Profile.objects.all()) return render(request, 'profile/profile_filter.html', {'filter': f}) filter.html {% for profile in filter.qs %} <img class="img-thumbnail account-img center" src="{{ MEDIA_URL }}{{ user.profile.image.url }}" width="100" class="img-fluid mx-auto d-block" alt="Card image cap"> <div class="card-body padding-success"> <h3 class="marker">{{ user.first_name }} {{ user.last_name }}</h3> <h3 class="marker">City: {{ user.profile.city }}</h3> <br><button type="submit" class="small" value="submit" href="{% url 'register' %}">Message?</button> </div> </div> {% endfor %} -
Django CSRF token error when Chrome developer tools is open
I've been getting a very strange issue with Chrome only the last few days and I cannot pinpoint what had gone wrong. Essentially, I'm getting a consistent CSRF error on form submissions only when the developer tools panel is open. I do not get the error when the panel is closed. This makes debugging certain things nigh on impossible. There have been no changes to the middleware or CSRF token handling that I am aware of (I'm not the only dev on the project, but I have sense checked the commits). The version of Chrome is 71 (released December 4th, long before this started happening), so I doubt it's specific to the browser. I'm just wondering if anyone else has experienced anything similar? The Django error is: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. -
Django and Elasticbeanstalk: a column that has been deleted on local hasn't been deleted on RDS
I deployed my project into eb and a form submission doesn't work on eb even though it works on local. And I found the cause. One of the attribute of a model that is not allowed to be null still remains on RDS even though I removed it in the past. Log error is like this ERROR: null value in column "a_variable" violates not-null constraint How can I handle with this problem? Is there a way to remove the column manually on RDS? I'm using PostgreSQL as the db engine. -
Self not defined inside forms.py class (forms.Form)
The error NameError: name 'self' is not defined My forms.py class PersonForm(forms.Form): name = forms.CharField(required=False) job_title = forms.CharField(required=False) status = forms.TypedChoiceField(choices=Person.STATUS_CHOICES) project = Project.objects.get(users=self.request.user, pk=self.kwargs.get('pk')) company = forms.ModelChoiceField(queryset=project.companies.all(),required=False) new_company = forms.CharField(required=False) note = forms.CharField(required=False) def __init__(self, *args, **kwargs): super(PersonForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' def clean(self): return self.cleaned_data I want to filter the 'queryset' on the 'forms.ModelChoiceField' field 'company'. Based on the companies of the project the user has access to. How would I do that? Can I access request.session data as well here? -
How to modify a {% block %} within a template tag?
I've an inclusion_tag called 'content_blocks' defined. And I want to insert some js in to a {% block %} defined in base template. # base.html <html> <body> {% content_blocks %} # content_blocks tag will be used here.. ... ... {% block js %} {% endblock %} </body> </html> # custom_tags.py @register.inclusion_tag('tags/content_blocks.html') def content_blocks(): content_type = ... # some content type, obtained from somewhere else # todo: depending on 'content_type', insert some js in to {% block js %} # how? .... other stuff Is this doable? I can't put the js in tag template because then it outputs it middle of the page (This js code needs JQuery and it's loaded at end of the page) -
Django Multiple Choice Field Options depend on value of Drop-down Menu
How to display one of several sets of Multiple Choice Field options based on the on value of currently selected in a drop-down menu? -
check condition in permission class
Why can't I check the condition in the permission class ? class ViewUserLeaveRequest(BasePermission): def has_permission(self, request, view): id = view.kwargs['id'] user = User.objects.get(id = request.user.id) print('this is user ', user) print(id) print(user.id) group = list(user.groups.all()) permison = group[0].permissions.all() if permison.get(name='can view leave request') or user.id == id: return True else : return False Everything is fine I am getting id from kwargs and I want to return True if user's group has the can view leave request or if the requested user's id equals the id in the kwargs. -
Reverse for 'profile_settings' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['users\\/profile\\/settings\\/(?P<pk>[0-9]+)$']
I have CustomUser and Profile model. Both tables have a one to one relationship. I used a post_save signal so, whenever a user is created an empty profile is automatically created. Profile only have an updateView because it is already created when a user is created. Problem : Whenever I access profile, I get this error. "Reverse for 'profile_settings' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['users\/profile\/settings\/(?P[0-9]+)$']" I am definitely making a mistake in template. Attaching all the relevant code snippets below. models.py class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) contact_mobile = models.CharField(max_length=11, null=True, blank=True) shipping_id = models.ForeignKey(Shipping, related_name='profile', on_delete=models.CASCADE, null=True, blank=True) biography = models.CharField(max_length=700), def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) post_save.connect(create_profile, sender=CustomUser) views.py class ProfileSettingsView(UpdateView): model = Profile form_class = ProfileSettingsForm pk_url_kwarg = 'pk' context_object_name = 'object' template_name = 'profile_settings.html' def get_object(self): pk = self.kwargs.get('pk') return get_object_or_404(Profile, id=pk) def get_context_data(self, **kwargs): c_object = self.get_object() context = super(ProfileSettingsView, self).get_context_data(**kwargs) context['user'] = c_object.user context['shipping_id'] = c_object.shipping_id context['contact_mobile'] = c_object.contact_mobile print('------------------------------------------------------') print('context: ', context) return context urls.py path('dashboard/', views.dashboard, name='dashboard'), path('profile/settings/<int:pk>', views.ProfileSettingsView.as_view(), name='profile_settings'), dashboard.html <div class="col-lg-3"> <nav class="account-bar"> <ul> <li class="active"><a href="{% url 'users:dashboard' %}">Dashboard</a></li> <li><a href="{% url 'users:profile_settings' pk=object.id %}">Profile Settings</a></li> … -
Upgrade Django-cms from 3.2.3 to 3.5
I try to upgrade a django-cms site from 3.2.3 to 3.5 but it doesn't work. I upgrade version by version (from 3.2.3 to 3.3 then 3.3 to 3.4). It was OK until I upgrade from 3.4 to 3.5 I had multiples errors when I do manage.py migrate : Table cms_treenode doesn't exit Key is duplicated The column "node_id" doesn't exist. (The errors are in migrations files, so I tried to modify them directly, so one error disappears and another appears, this is why I listed multiple errors) Current versions: Django=1.8.15, Postgres=9.5.14 Does anyone upgrade from django-cms 3.2 to 3.5 correctly without bugs? Thanks :) -
On Mac, what should PYTHONPATH be set to in order to use "python manage.py run_command"?
I'm using Mac 10.13.6 with Python 3.7. I use PyCharm for development. Although I can run commands fine in the PyCharm management console, when I try and run the same commands in a terminal, I get errors complaining taht I don't have Django installed. For instance localhost:mainpage_project davea$ python manage.py runstats Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Perhaps I defined my PYTHONPATH incorrectly, but I set it to my Python executable localhost:mainpage_project davea$ which python /usr/local/bin/python localhost:mainpage_project davea$ echo $PYTHONPATH /usr/local/bin/python What should be the value of PYTHONPATH? I'm able to run the command fine within PyCharm, it's only in the terminal that things start throwing errors. -
Error "collectstatic --noinput" in heroku with Github
I have created and worked on a Django application (Simple website with user registration and login) and now i want to try deploying it into heroku. I have already uploaded my full code to GitHub and I'm using the deployment method through GitHub on Heroku. I connected my GitHub directory to heroku and started the deployment, but an error came up. I've searched everywhere but i can't find a solution anywhere. here's the error -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 125, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 313, in listdir for entry in os.listdir(path): FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_e6d59abe7139c45ae94e60de651b660c/sitoassociazione/static' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may … -
django inspectdb ORA-00904 "IDENTITY_COLUMN"
I'm currently trying to get Django (version 2.1.5) models from existing Oracle 11 database by python manage.py inspectdb, but this error still occurs: # Unable to inspect table table_name # The error was: ORA-00904: "IDENTITY_COLUMN": invalid identifier I've tried to use different Djangos. E.g. with 2.0, error didn't occur, but no text for models was created. Another questions from this topic here on SO were not helpful. Based on this link, I think error occurs because I have no primary key in the table, but since I'm not sure, I don't want to make any changes to existings database. Does anybody solved this problem? -
Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x9d in position 41624: character maps to
I'm trying to import a CSV file with Django-MySQL, using django-import-export module. My data looks like below; laptops_name laptops_url laptops_price laptops_image brand_name "Acer Predator Helios 300 PH315 144Hz (i7-8750H, 8GB, 1TB, 128GB, NV GTX1060, W10)" https://computermania.com.bd/product/acer-predator-helios-300-bd-price/ 132900 https://computermania.com.bd/wp-content/uploads/2017/08/acer_predator_helios_evl1L-240x240.jpg Computer Mania "Acer Predator Helios 300 PH315 144Hz (i7-8750H, 16GB, 1TB, 128GB, NV GTX1060, W10)" https://computermania.com.bd/product/acer-predator-helios-300-ph315144hz-refresh-rate-i7-8750h-16gb-1tb-128gb-nv-gtx1060-w10h/ 138900 https://computermania.com.bd/wp-content/uploads/2017/08/acer_predator_helios_evl1L-240x240.jpg Computer Mania "Asus TUF FX504G 15.6ƒ?? FHD Gaming Laptop (I5-8300H, 4GB, 1TB, GTX1050 4GB)" https://computermania.com.bd/product/asus-tuf-fx504g-bd-price/ 73900 https://computermania.com.bd/wp-content/uploads/2018/04/asus_tuf_fx504g_de40_SCd3d-240x240.jpg Computer Mania "Asus TUF FX504G Gaming Laptop (I5-8300H, 8GB, 1TB, GTX1050 4GB)" https://computermania.com.bd/product/asus-tuf-fx504g-15-6-fhd-gaming-laptop-i5-8300h-8gb-1tb-gtx1050-4gb/ 77900 https://computermania.com.bd/wp-content/uploads/2018/04/asus_tuf_fx504g_de40_SCd3d-240x240.jpg Computer Mania "Dell Alienware M15 Gaming Laptop (I7-8750H, 16GB, 1TB+8GB+256GB, GTX1070 8GB, W10)" https://computermania.com.bd/product/dell-alienware-m15-price-in-bd/ 199000 https://computermania.com.bd/wp-content/uploads/2019/01/dell_alienware_15_m1_DNpO4-240x240.jpg Computer Mania But I get an error like the title of this question. My django model is like below: class ProductLaptop(models.Model): laptops_name = models.CharField(max_length=500) laptops_url = models.CharField(max_length=500) laptops_price = models.IntegerField(null=True, blank=True) laptops_image = models.CharField(max_length=400) brand_name = models.CharField(max_length=20) def __str__(self): return self.laptops_name Any solution for this problem? -
I am stuck with Levenshtein. It keeps saying "No module named 'Levenshtein'. I have installed Levenshtein. What should I do?
File "/Users/karanpraharaj/Desktop/IIIT Hyderabad - Spring 2019/Project - CV Jawahar/RMS-master/RMS/Each_Paper_Analytics/views.py", line 7, in import Levenshtein ModuleNotFoundError: No module named 'Levenshtein' -
Django Use values in static files
I have some standard colors set in my settings.py colors = [ ("blue", "#4a3ed0"), ("green", "#4ad041") # And some more ] I load my static files using: <link rel="stylesheet" href="{% static 'defaults/default.css' %}"> And I want to access green in my default.css. I made a template tag (named utils): @register.simple_tag def get_settings_color(color): for c in settings.colors: if c[0] == color: return c[1] In my default.css I tried to access "get_settings_color" but it didnt work. defaults.css: {% load utils %} div.green{ color: #fff; background-color: {{ get_settings_color:"green" }} /* And some other fields */ }