Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Making requests to views always running asynchronously in Django
I'm currently using the following API: https://github.com/LevPasha/Instagram-API-python to make requests to Instagram. However, every time I need to pull info from the API, I'm required to sign into an account, which takes an extra 3 or 4 seconds. In order to make this process more efficient, and not to mention experience login throttling from Insta, I'd like a view that keeps the account logged in. Is this possible with a single server? I kindly appreciate for any help. -
Disable multiple search in django restframework search_filter
Is there anyway to disable multiple search in Django-rest-framework using SearchFilter? By default django-rf will apply multiple search if whitespace and/or comma appear on search string. xyz.com/?search=x,y This search will return results contain either x or y (seperated by comma). I would like to make it return results contain "x,y" as parts of string. -
Why is the project packaged with pyinstaller so big?
Package the Django project with pyinstaller, and finally pack the folder with 251M. In the folder, Qt5WebEngineCore.dll is 70.1M and the third-party library folder of pyqt5 is 95M What's more? there are many dll files about pyqt5, the folders of the third-party libraries used are also packaged, as shown in the following picture how can we make the packaged project smaller? Do you have a good idea?enter image description here -
Prepopulate Django Forms on Jquery Page Redirect
I have a page that displays the history of some of the previous form submissions by a user. I have used the following code to extract this data from a table on the page: $( "#rerun-conv-input" ).click(function() { // alert( "Handler for .click() called." ); console.log($(".edf-run-detail.active.show").children()); var json_input_list = new Array(); $table = $(".edf-run-detail.active.show") $table.find('tr').each(function (i, el) { var $tds = $(this).find('td'); var value = $tds.eq(1).text(); json_input_list.push(value); }); var json_input = { "input1" : json_input_list[0], "input2" : json_input_list[1], "input3" : json_input_list[2], "input4" : json_input_list[3], "input5" : json_input_list[4], } ... window.location.assign("{% url 'form-conversion' %}"); ... How do I include the previously submitted form inputs from json_input_list through my page redirect? I believe I have to do it by passing it through the URL, but I am worried my inputs might be too large to fit the size of a URL. Any help is much appreciated. Thanks! -
Expected a dictionary, but got str Django Rest Framework
Right now I am creating a user department with a list of users that are a foreign key back to the main user model. I had this working yesterday, but for some reason I screwed it up. I imagine it has something to do with the serializers. I want to be able to post a list of users in this format ['jack', 'tom'] However, even using the raw data api this is not allowing me to do this. Here is my code: Serializers: class DepartmentSerializer(serializers.ModelSerializer): user_department = UserSerializer(many=True) class Meta: model = Departments fields = '__all__' class DepartmentUpdateSerializer(serializers.ModelSerializer): user_department = UserSerializer(many=True) class Meta: model = Departments fields = ['department_name', 'department_head', 'user_department'] I swear yesterday it was allowing me to select from a list of users in the api. I could also post and it would work from the front end. However, now whenever I create a department it's expecting a dictionary, which I am not trying to pass. -
How to make migrations for app in django 1.5
Since the makemigrations command is not available in Django 1.5, I am not sure how to use migrations to sync all django apps. The migrate command does not solve the issue and I instead get a GhostMigrations error and "! These migrations are in the database but not on disk:" -
Django seperating apps?
I am working on a Learning Management System. At this moment I want to make a calendar app that will display a calendar and show "events". These events can either be a project or a training program. But I am not sure what would be the best design choice in terms of seperating the apps. Should I add the models for projects and trainings in my calendar app or should these two be seperated apps that I can connect to an Event model in the calendar app? -
Django completely broken even after reinstalling it
Let me preface this by saying that my knowledge on django and web development in general is very superficial. I was messing around with security configs on my django project, trying to make my website use https (which since then I learned is not that easy to do) but I got it into a redirect loop I believe (the website never loads). I tried to revert all my changes but couldn't get to run the website locally. After looking for answers on google in vain I decided to start the project from scratch (I had just started it anyway). But now even that doesn't work, even the Writing your first app tutorial doesn't work. After that I reinstalled python and all the dependencies expecting that to clear every possible thing that I had changed but it didn't, still the same problem, websites never load trying to use https. Where else could the problem in my system be? -
How to set the endpoint to publish with Django REST Swagger
I have a large API REST project with Django Rest Framework, and I want to document it with Django REST Swagger, but I want this Swagger documentation to include only some of the endpoints of my whole project. This is my urls.py where I set Swagger in my project: from rest_framework_swagger.views import get_swagger_view urlpatterns = i18n_patterns( path('api-token-auth/', views.obtain_auth_token), path('', include('FrontEndApp.urls')), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('docs/',get_swagger_view(title="Intellibook API")), path('rosetta/', include('rosetta.urls')), path('general/', include('GeneralApp.urls')), path('operations_manager/', include('OperationsManagerApp.urls')), path('payments_manager/', include('PaymentsManagerApp.urls')), #path('providers_manager/', include('ProvidersManagerApp.urls')), path('rates_manager/', include('RatesManagerApp.urls')), path('reports_manager/', include('ReportsManagerApp.urls')), path('reservations_manager/', include('ReservationsManagerApp.urls')), path('users_manager/', include('UsersManagerApp.urls')), path('excursions_manager/', include('ExcursionsManagerApp.urls')), path('invoices_manager/', include('InvoicesManagerApp.urls')) ) Currently, Swagger publishes all the endpoints that are in all urls.py along the whole project. I want to set it to publish only the endpoints in ursl.py of only on of the apps of the project. -
How can I get the objects from this model?
I'm trying to create an address model/views/... that works and I got the model working, but I'm trying to access the data it contains and it's not working. Here is the model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nick_name = models.CharField('Nick name', max_length=30, blank=True, default='') bio = models.TextField(max_length=500, blank=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') # Address = models.ForeignKey('Address', on_delete=models.CASCADE) # If we don't have this, it's going to say profile object only def __str__(self): return self.user.username #return f'{self.user.username}' # it's going to print username Profile def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class Address(models.Model): users = models.ManyToManyField(Profile, blank=True) name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60, default="Miami") state = models.CharField(max_length=30, default="Florida") zipcode = models.CharField(max_length=5, default="33165") country = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Address' def __str__(self): return self.name I'm trying to access all the addresses that a user can have. I tried: # TESTS allAddresses = Address.objects.all() print(allAddresses) and for the address objects it gives me: <QuerySet [<Address: Elizabeth>, <Address: Work>]> But if I try to filter it by user, like this: allAddresses = Address.objects.all().filter(users='arturo') print(allAddresses) it gives me an error: invalid literal for int() … -
Get value list from ManytoMany model
I would like to retrieve a list of values on the format ['BMW', 'Mercedes', 'Audi'] (these are the three selected out from a list of 50+ different car makes made in a multiple select form field/list. Values exist in a ManyToMany: class CarMakeModel(models.Model): Make = models.CharField(max_length=30) class Product(models.Model): selection = models.ManyToManyField(CarMakeModel) Now I would like to retrieve the selection made, e.g. in the shell: select = product.models.Product.objects.latest('id').selection.values('Make') This will return: <QuerySet [{'Make': 'BMW'}, {'Make': 'Mercedes'}, 'Make': 'Audi'}] How do I get this QuerySet reply into this format ['BMW', 'Mercedes', 'Audi'] ? I have tried list(select) and tuple(select) which returns: [{'Make': 'BMW'}, {'Make': 'Mercedes'}, 'Make': 'Audi'}] and ({'Make': 'BMW'}, {'Make': 'Mercedes'}, 'Make': 'Audi'}) but already now it feels I have taken too many steps for a seemingly simple request. My question is how do I more correct achieve my aim? -
Forbidden (403) CSRF verification failed. Request aborted. Django Admin
I've been using the Django admin panel for my project the entire time and suddenly after I cleaned my cookies it just won't work again it keep sending me this error: Forbidden (403) CSRF verification failed. Request aborted. Help: Reason given for failure: CSRF token missing or incorrect. -
Wagtail routable page view with ajax content loading on click
I have an app where i display contributor page with content like stories, videos and articles. Stories, videos and articles are different page models. template engine: Jinja framework: Django CMS: wagtail I am able to load ajax content in to the tab successfully by creating separate view and corresponding url in urls.py with below ajax settings. But if i try to use Wagtails routable page feature i get 404. Ajax settings excerpt: settings = jQuery.extend(true, {}, { type: 'get', dataType: 'json', url: vUrl, beforeSend: function (jqXHR, settings) { console.log(`URL ${settings.url}`) $tab.html('<br>'); $paneHeader.removeClass(css).addClass(css); $el.trigger('tabsX:beforeSend', [jqXHR, settings]); }, success: function (data, status, jqXHR) { setTimeout(function () { // $tab.html(data); //Use Json data instead of html $tab.html(data.html); $pane.tab('show'); $paneHeader.removeClass(css); }, 300); }, error: function (jqXHR, status, message) { $paneHeader.removeClass(css); }, } @route(r'^/contributors/(?P<slug>[-\w]*)/articles') def show_articles_contributed(self, request): if request: print("Inside AJAX") articles = Contributor.get_articles_by_authors(self.id) html = render_to_string("organisms/latest_articles.html", {"objects": articles}) return JsonResponse({"html": html}, safe=True) else: return super(ContributorPage, self).serve(request) URL printed from console.log URL /contributors/test-author/articles Failed to load resource: the server responded with a status of 404 (Not Found) class ContributorPage(RoutablePageMixin, PhoenixPage): first_name = models.CharField(max_length=255, blank=True, default="") last_name = models.CharField(max_length=255, blank=True, default="") nickname = models.CharField(max_length=1024, blank=True, default="") PhoenixPage is nothing but base page with metadata which actually … -
Django multiple models in CreateView
Hello I am trying to create a view with the following: model.py class a (models.Model): # fields filled in with information class b (models.Model): # fields filled in with information . . . class n (models.Model): # fields filled in with information views.py class Create(PermissionRequiredMixin, CreateView): How do I pass models a thru n, to the view and use them individually? Models a thru n will have no relationship with each other (i.e. ForeignKey nor ManyToManyRelationship, etc). The view will be a form which I would then process after it is submitted. -
Django API to create new user
I'm trying to create user creation API, but I'm not sure if I'm doing this ok because I get something like this: Am, I doing something wrong? Because I doubt this should look like this, this is my code: serializer.py from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email') views.py from rest_framework import status from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.permissions import AllowAny from .serializer import * @api_view(['POST']) @permission_classes((AllowAny,)) def user_creation(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
What attributes should options use when creating a custom Django form?
I have an existing "custom" Django form and I'd like to add a select/option list to it which will be used to populate the value of a foreign key field. I realize this is not the best way to approach this, but the form's markup is heavily customized and I don't want to rewrite it using the Form class. So, what attributes should I used in the select/option elements in order to get Django to populate the foreign key field. I've tried variations of the following, without success. (The model is structured correctly and I'm able to populate the field using an instance of the relation from within the shell.) <div class="mui-select"> <select id="id_column_name" name="column_name"> <option value="{{relation.id}}">{{relation.name}}</option> </select> <label>Select Relation</label> </div> In case it helps nudge anyone along, I believe Rails uses something like the following for the select name attribute, model[relation][id] -
django (DRF) serialize model object to non model object?
I have a Django Model User e.g. class User(AbstractBaseUser, PermissionsMixin,): first_name = models.CharField(max_length=20, default=None) last_name = models.CharField(max_length=20, default=None) email = models.EmailField(unique=True, max_length=100) user_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) I want to derive a non-model based object from this User model object say Friend (I have no need to persist the Friend obj in a table, this would be sent in response then no longer required). I would like to send a list of Friends to the user each of which are derived from the respective User obj. I was exploring the idea of creating a FriendSerilizer class e.g.class FriendSerializer(serializers.Serializer): class Meta: fields = ('avatar', 'user_id', 'first_name', 'last_name', 'hidden') With the idea of somehow passing the User obj to the Friend serializer generating the necessary temporary Friend obj. Is this possible and if so is it a reasonable solution to creating the Friend obj or is there a better (Django friendly) way of creating the desired Friend object? -
OperationalError: no such column but column doesn't exist anywhere
I am building a Django website, and I am a relative beginner. However, this error baffles me so please let me know what might have happened. I am getting an error django.db.utils.OperationalError: no such column: metadata.id But no where in my code is metadata.id, nor in the database I am using. So I am really confused about where this has come from. Presumably I have tinkered somewhere where I shouldn't. My question is then, does the beginning of this message give any indication as to where I should be looking for the error? I also have this message In template .../kinbank2/templates/base.html, error at line 0 Which makes it difficult to find a line or file to look at. Thanks, Sam Error traceback Performing system checks... System check identified no issues (0 silenced). February 28, 2019 - 22:04:54 Django version 2.0.4, using settings 'kinbank2.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /language/ Traceback (most recent call last): File "/Users/sp16194/anaconda/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/sp16194/anaconda/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: metadata.id The above exception was the direct cause of the following exception: Traceback (most recent … -
Django disable a specific form field's validators
Is it possible that disable a specific form field's validator in views.py to reuse an existing ModelFrom? For example, in tblstudentinfomodelform(forms.ModelFrom), I set LastName,Username and Firstname to validators=[alphanumeric]. When user_1 load the form and save it, all validators are applied. But when user_2, let's say admin login, I need that LastName's validators is disabled when running is_valid(). Is that possible except creating a new form? Thank you. Some codes here, class tblstudentinfomodelform(forms.ModelForm): LastName = forms.CharField(max_length=30, required=True, validators=[alphanumeric]) Username = forms.CharField(max_length=25,required=False,validators=[alphanumeric]) Firstname = forms.CharField(max_length=30,required=False,validators=[alphanumeric]) -
Django Models getting "ValueError: invalid literal for int() with base 10: " After calling objects.update_or_create
I'm having trouble using Django's update_or_create method on the model below. I get this error: ValueError: invalid literal for int() with base 10: ' ' The error seems to always throw on the last line of the update_or_create, because when I added verified=False (which has a default value of False) to the statement, the error traced back to the line with verified=False instead of the line shown below. My models: class Addresses(models.Model): customer = models.ForeignKey('Customers', on_delete=models.CASCADE) address_name = models.CharField(max_length=45) company = models.CharField(max_length=45) street1 = models.CharField(max_length=60) street2 = models.CharField(max_length=30, blank=True, null=True) street3 = models.CharField(max_length=30, blank=True, null=True) city = models.CharField(max_length=45) state = models.CharField(max_length=45) zip = models.IntegerField() country = models.CharField(default='US', max_length=45) phone = models.IntegerField(blank=True, null=True) residential = models.BooleanField(default=True) verified = models.BooleanField(default=False) class Customers(models.Model): customer_name = models.CharField(max_length=75) email = models.CharField(max_length=60, blank=True, null=True) phone = models.IntegerField(blank=True, null=True) ss_customer_id = models.IntegerField(blank=True, null=True, unique=True) The function: def addAddress(self, address, customer_id): if address['name'] is not None and address['street1'] is not None and address['city'] is not None: if address['state'] is not None and address['postalCode'] is not None: address, created = Addresses.objects.update_or_create( address_name=address['name'], company=address['company'], street1=address['street1'], street2=address['street2'], street3=address['street3'], city=address['city'], state=address['state'], country=address['country'], phone=address['phone'], customer=customer_id #error thrown here ) address.save() return address return False The data: address = { 'name': 'Johnny Appleseed', 'company': … -
Why won't Python package install from my personal PyPI server?
I've created a personal PyPI "packages" server on a Debian 9/Nginx box so that I can make my server builds deterministic. I pin all my Python packages and need to ensure that the exact versions of my Python packages as well as their sub-dependencies are always available whenever I need to rebuild my e-commerce servers. I populated this server with my required packages using the pip2pi package. But when I run the "pip install" command on a client server to install my packages, I'm getting the following error: Looking in indexes: https://packages.example.com/simple Collecting Django==1.8.4 (from -r requirements.txt (line 2)) Collecting django-extensions==1.5.7 (from -r requirements.txt (line 3)) Could not find a version that satisfies the requirement django-extensions==1.5.7 (from -r requirements.txt (line 3)) (from versions: ) No matching distribution found for django-extensions==1.5.7 (from -r requirements.txt (line 3)) I have about 40 packages in my requirements file so this is just an example of what happens. The Django package will get installed but pip will fail with the django-extensions package. If I run this command on any of my client servers, I get the error shown above: pip install -r requirements.txt The requirements file looks like this: -i https://packages.example.com/simple Django==1.8.4 django-extensions==1.5.7 (more packages) … -
Django User Model with ManyToMany relationship, how to update/ create new profile with relationship?
I have a class that has a one to one relationship with my User class. In this class (called UserLocations), I have a field that is a ManyToManyField on another class (we will call this model Locations). In my Locations class, I have a field called 'abbreviation' which is a four character abbreviation of the location name. I have a front end website where an admin can create a new user or update an existing users locations (based on the abbreviation field). When I am going to create a new user, how would I set/ update that ManyToMany field based on the 'abbreviation' field? It is a list of abbreviations that tie to that 'abbreviation' field in the Locations model. -
Shared Modules in a Django project
Based on some advises, I created a separate folder in my Django project with init.py to put all the shared classes and functions in one place. I tried to import them using ..folder.module but it doesn't work. What's the right method for sharing class and functions in a Django project? -
Pass additional parameters with Django signals
Is there any way to pass additional parameters to instance I'm saving in DB to later access them after the instance is saved? Brief example of my case: I'm using Django's signals as triggers to events, like sending a confirmation email, executed by other processes, like workers. I'm willing to specify which instance and when should trigger the event, and which does not: sometimes I want created/updated records to trigger series of events, and sometimes I want them to be processes silently or do some other actions. One solution for this is saving desired behaviour for specific instance in model's field like JSONField and recover this behaviour at post_save, but this seems very ugly solution. I'm using post_save signal as verification of instance was correctly saved in the DB, because I don't want to trigger event and a moment later something goes wrong while saving instance in DB. Instances are saved through Django Forms, backend routines and RestFramework Seralizers -
Load django form instance for form where dropdowns are dependent on each other
I have a ModelForm that has 5 dropdowns on it. Initially they are shown one dropdown, on user selection (jquery on change event) - Ajax fires off the request to a view function - which renders the queryset in a dropdown and is put into the current DOM via jquery. I followed this tutorial to set it up (repeating the process for my 5 dropdowns). My issue stems when I go to edit a saved form. Similar to the end of the tutorial, I can setup my form using the instance items and it's ok. If I change the last dropdown and save the form it updates as expected. But if I change any other item and it generates options that are not in the initial queryset, it kicks off errors saying Select a valid choice. That choice is not one of the available choices. Should I just generate the queryset again in a clean_ method for each input and force it to be validated if it matches those? Is there a better way to handle dependent dropdowns in forms? My code mimics the tutorial almost exactly - except with a few additional inputs, chained in exactly the same way …