Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using .first to limit django queryset results in TypeError at /path/ object of type 'Product' has no len()
I have rows in a database where some fields are repeating, such as: Collection name | Product ID | Product Name | Image URL -------------------------------------------------------- Dusk |001 | Chair |/images/001.jpg Dusk |002 | Desk |/images/001.jpg Dusk |003 | Table |/images/001-t.jpg Rome |004 | Chair |/images/002.jpg Rome |005 | Desk |/images/002-d.jpg Rome |006 | Table |/images/002-t.jpg Noel |007 | Chair |/images/003.jpg Noel |008 | Desk |/images/003.jpg Noel |009 | Stool |/images/003.jpg There can be multiple rows having the same collection name, and some other fields may be the same also, such as the image url. What I am trying to do is to return all rows where the collection name is distinct, but only the first row of each one. I'm tyring to do this in a django view using '.first()', but it gives an error that my model object has no length. I know records are being returned so that isn't the issue, but I'm not sure what the issue could be. Here is the code I am using in my views.py: def bedroom_view(request): template = loader.get_template('/myapp/test_site/main_page/templates/main_page/bedroom.html') products = xroduct.objects.filter(product_category='Beds').first() page = request.GET.get('page', 1) paginator = Paginator(products, 9) try: prods = paginator.page(page) except PageNotAnInteger: prods = paginator.page(1) except EmptyPage: prods … -
How to fix : RelatedObjectDoesNotExist - User has no profile
I'm adding some features on a Django application. I added the corresponded model MealCategory but when I want to access the application I encounter the following error : django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: User has no restaurant. -
Azure App Service ImportError: libmysqlclient.so.18: cannot open shared object file: No such file or directory
On App Azure Linux with Python, the Mysql module seem not work : 2018-12-24T19:11:38.215760010Z import _mysql 2018-12-24T19:11:38.215763810Z ImportError: libmysqlclient.so.18: cannot open shared object file: No such file or directory ... 2018-12-24T19:11:27.536810347Z django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. 2018-12-24T19:11:27.536813747Z Did you install mysqlclient? requirement : django mysqlclient Has anyone ever managed to run django on azure web app? -
How to import python function from another file into django views
I am trying to call a function from a python file that is located outside the django project directory from views.py. I have tried importing the python file but running the django server says "no module named xxxx". There is a django project let's say "scrapper" and there is an app in that project named "parser". There is another directory named "test" that has same location as "scrapper". What I want to do is to import a python file from test into parser.views and call a function from views. Importing like this "from test.abc import xyz" throws error "no module named abc" -
How to fix 'django.db.utils.OperationalError: near "None": syntax error' db.sqlite3?
I am attempting to create a user model for my Django REST framework and, sadly, I'm experiencing some unexpected difficulty: when I run 'python manage.py makemigrations' everything functions as it should, but, when I try to run a migration, I am greeted with this error 'return Database.Cursor.execute(self, query) django.db.utils.OperationalError: near "None": syntax error'. I've tried altering the code in the models.py but it still yielded the same results, even if I set the user model class to only have one id field. I am using django version 1.11.17 and drf version 3.9.0 models.py: class User(models.Model): id = models.AutoField(primary_key=True) email = models.CharField(unique=True, null=False, max_length=200) phone = models.IntegerField(unique=True, null=False) first_name = models.CharField(null=False, max_length=200) last_name = models.CharField(null=False, max_length=200) is_active = models.BooleanField(_('active'), default=False) last_seen = models.DateTimeField(auto_now=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) avatar = models.CharField(null=True) migrations/0001_initial.py: class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('email', models.CharField(max_length=200, unique=True)), ('phone', models.IntegerField(unique=True)), ('first_name', models.CharField(max_length=200)), ('last_name', models.CharField(max_length=200)), ('last_seen', models.DateTimeField(auto_now=True, null=True)), ('updated_at', models.DateTimeField(auto_now=True, null=True)), ('created_at', models.DateTimeField(auto_now_add=True, null=True)), ('avatar', models.CharField(null=True)), ], ), ] I want to be able to successfully run the migration. -
Postgresql skipping some/many write queries when used along with python crawlers
i am using postgres paired with django(python) and application is crawling internet for specific kind of data. As the crawlers find anything of their use they write it to the database. Now as the speed of crawlers is high and they are querying database by get_or_create(in django which checks for if the data is already in the database or not if it is not present then it makes a new row of it) All the cores on my machine are engaged to almost 99%. In that case when i trace the process,the postgres is skipping the write command for some or many instances.What can be the reason? Any recommendations in terms of change in architecture? traced the crawler procedure manually and the process was printing the data it found but was not added to the postgres. That confirmed the data was getting lost. -
How do I "return index(request)" on successful form submit in Django 1.11
I am trying to use Toastr to pass status messages upon completion of a form. If the form is valid it returns you to the index using "return index(request)" I want to pass context through this. I am running Python 3.6 and Django 1.11, using Modelorm. I have tried passing context=var_list as well as passing the variables individually. Line 15-34 of my views.py def add(request): form = CustomerForm() if request.method == "POST": form = CustomerForm(request.POST) if form.is_valid(): form.save(commit=True) notification_vars = {"toastr_title": "SUCCESS!", "toastr_message": "The Customer has been added to the database", "toastr_type": "success",} return index(request, context=notification_vars) // THIS IS WHAT I NEED TO WORK page_vars = { "page_title": "Add Customer", "page_icon": "fa-address-book", "toastr_title": "", "toastr_message": "", "toastr_type": "", "form": form} return render(request, 'customers/add.html', context=page_vars) This is the toaster code in my footer, and why I always have to pass the variables as blank unless I want to pass a message {% if toastr_message %} <script> var title = '{{ toastr_title }}', message = '{{ toastr_message }}', type = '{{ toastr_type }}', options = {}; toastr[type](message, title, options); </script> {% endif %} What I want to do is on successful form submission, it passes the context back tot he index page … -
What are some heuristics for structuring scalable model relationships in Django?
I don't know much about database structure. Nonetheless, I'd like to structure my models in such a way that is at least somewhat efficient. For example, I have the standard Django User model. When users sign up, they create a profile, select multiple activities (on an interface which shows available activities), and rank themselves according to said activities: from django.db. import models from django.contrib.auth.models import User class UserProfile(models.Model): user = OneToOneField(User) ... display_name = models.CharField(max_length=20) class UserActivity(models.Model): RANKINGS = ( (0, '0 - Newbie'), (1, '1 - Advanced'), (2, '2 - Expert'), ) activity = ManyToManyField(Activity, related_name="activities") rank = models.PositiveSmallIntegerField(choices=RANKINGS) class Activity(models.Model): label = models.CharField(max_length=20) description = models.TextField() This seems fine and good to me, but often things seem fine and good and... well, they aren't. I'm wondering if there's a set of standards or heuristics that I can use for structuring models. What should I be thinking about when I create ManyToMany relationships, or ForeignKeys for example? -
Trouble loading fixture to ClearDB locally. Django migration raises django.db.utils.OperationalError: (1060, "Duplicate column name '") locally only
I'm using Django. I have a large 500+ MB fixture I need to add to MySQL Database on Heroku. I'm using the ClearDB add-on. After connecting the ClearDB using the correct credentials, if I try to run manage.py migrate it gives me a 1060, Duplicate Column error. If I push my files to heroku, and run heroku manage.py migrate it works perfectly. Here is the full trace-back for the error: Applying django_celery_beat.0005_add_solarschedule_events_choices_squashed_0009_merge_20181012_1416...Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Program Files\Python36\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute return self.cursor.execute(query, args) File "C:\Program Files\Python36\lib\site-packages\MySQLdb\cursors.py", line 255, in execute self.errorhandler(self, exc, value) File "C:\Program Files\Python36\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler raise errorvalue File "C:\Program Files\Python36\lib\site-packages\MySQLdb\cursors.py", line 252, in execute res = self._query(query) File "C:\Program Files\Python36\lib\site-packages\MySQLdb\cursors.py", line 378, in _query db.query(q) File "C:\Program Files\Python36\lib\site-packages\MySQLdb\connections.py", line 280, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1060, "Duplicate column name 'timezone'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\jermo\Alpha\Alpha\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line … -
How can django redefine DJANGO_SETTINGS_MODULE when I run tests?
I have a "settings" directory in the root of my project. It contains different files with settings: ./settings/tests.py ./settings/testing.py ./settings/production.py I want to use tests.py for unit tests (I use testing.py for preproduction application run), so. In manage.py file I wrote these code: ... if 'test' in sys.argv: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.tests') else: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.production') ... When I run python manage.py test <app_name>, all the tests run perfectly and the settings/tests.py module is used. But when I run python manage.py test, Django loads settigns/testing.py file. When I rename testing.py file, everything works as I expect: tests.py module is loaded. Is there any logic about locating testing module for tests in Django? How can I disable it? -
uWSGI html caching compressed
I've been following uWSGI's documentation on caching and I'm hitting some really strange behavior. The first request comes from my django app and the second correctly comes from uWSGI cache. The problem is that the response coming from uWSGI is compressed after the html reaches a certain size. I created two django views to test this: def prime(request): from django.http import HttpResponse data = """<!doctype html> <html lang="es"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> </html>""" return HttpResponse(data) def info(request): import zlib import uwsgi from django.http import HttpResponse resp = uwsgi.cache_keys() print(resp) decompressed_data = zlib.decompress(uwsgi.cache_get(b'/prime/'), 16 + zlib.MAX_WBITS) return HttpResponse(decompressed_data) I make a request to /prime/ which primes the uWSGI cache. The next request is to /info/ which correctly shows the cached html. Without the decompress code, it would just print out the bytes of the compressed response. This is an issue because requesting /prime/ from the browser will return a un-renderable response. Here's my uWSGI config: [uwsgi] module = wsgi http = 0.0.0.0:80 master = true workers = 3 max-requests = 500 harakiri = 120 lazy-apps = true static-map = /static/=/static/ route=^/static/.* addheader:Cache-Control: public, max-age=3600 cache2 = name=html,items=100 ; create a cache for images with dynamic size … -
Creating a user profile to user auth django
I'm trying to create a profile for my user using django rest auth model, but when I'm sending the data to the user's creation, the user's image is not being filled, that is, it's getting null, I tried to send the node as much as image, as much as profile.image, but without success below my code follows: models\profile.py from django.conf import settings from django.db import models class Profile(models.Model): image = models.ImageField(blank=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.user.email serializers\user.py from rest_framework import serializers from rest_framework.validators import UniqueValidator from django.contrib.auth.models import User from src.v1.user.models.profile import Profile from .profile import ProfileSerializer class UserSerializer(serializers.ModelSerializer): profile = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( max_length=32, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(min_length=6, write_only=True) @staticmethod def get_profile(user): """ Get or create profile """ profile, created = Profile.objects.get_or_create(user=user) return ProfileSerializer(profile, read_only=True).data def create(self, validated_data): user = User(email=validated_data['email'], username=validated_data['username']) user.set_password(validated_data['password']) user.save() return user class Meta: model = User fields = ('id', 'username', 'email', 'password', 'profile') serializers\profile.py from rest_framework import serializers from src.v1.user.models.profile import Profile class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' class ProfileSerializerUpdate(serializers.ModelSerializer): class Meta: model = Profile fields = ('image',) views\user.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework … -
Limit Wagtail Custom Site Settings to Group or Site
I am trying to create custom settings on a site by site basis for head/footer information. I have registered the settings and I'm able to edit the settings for each site, but other sites can see/edit these settings: The code I have is: @register_setting class SiteSettings(BaseSetting, ClusterableModel): site_name = models.CharField(max_length=50) site_logo = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) banner_color = models.CharField( max_length=6, null=True, blank=True, help_text="Fill in a hex colour value" ) include_footer = models.BooleanField(null=True) panels = [ FieldPanel('site_name'), ImageChooserPanel('site_logo'), FieldPanel('banner_color'), FieldPanel('include_footer'), InlinePanel('footer', label="Footer", help_text='Select your contact/social media type and enter the phone number, email, or URL') ] I tried overriding SiteSwitchForm, but it doesn't seem to get called. # Override SiteSwitchForm class SiteSwitchForm(SingleSiteSwitchForm): site = forms.ChoiceField(choices=[]) class Media: js = [ 'wagtailmenus/js/site-switcher.js', ] def __init__(self, current_site, url_helper, **kwargs): initial = {'site': url_helper.get_action_url('edit', current_site.pk)} super().__init__(initial=initial, **kwargs) sites = [] for site in Site.objects.filter(site_name__exact=self.site_name): sites.append((url_helper.get_action_url('edit', site.pk), site)) self.fields['site'].choices = sites I also tried: def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(managed_by=request.user) But that doesn't apply to BaseSettings. Is there a way to make custom settings only visible to the group/site that owns the site? -
sorted by date and letters buttons python django
i have model "Package" contain a lot of object and i want in my template (dashboard.html) two buttons to sorted by date created or A-Z in my case display order by letters with : #views.py class PackageDashboardView(PackageAccessMixin,ListView): template_name = "packages/dashboard.html" queryset = Package.objects.all() .order_by('title','version__name').\ select_related('title', 'version').defer('title__metadata', 'validation', 'translations', 'diff_fields') if i change title by started will sorted by date my model: #models.py class Package(models.Model): title = models.ForeignKey('titles.Title', on_delete=models.PROTECT) version = models.ForeignKey(PackageMovieVersion, on_delete=models.PROTECT, null=True) started = models.DateTimeField(auto_now_add=True) -
Getting selected value from a dropdown menu django
I currently have a dropdown menu from which i want to get the chosen element from a user. How can I return the element to the views.py? I would like to keep the same visual but I can use any types of form ,option,select that could help me. <div id="tableDiv" class="dropdown"> <button id="tableButton" class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Rank <span class="caret"></span> </button> <ul id="tableMenu" class="dropdown-menu" aria-labelledby="dropdownMenuLink"> <li><a class="dropdown-item" href="#">Att1</a></li> <li><a class="dropdown-item" href="#">Att2</a></li> <li><a class="dropdown-item" href="#">Att3</a></li> </ul> </div> thanks -
AttributeError with django-rest-auth and django-rest-knox - Token Serializer
I am currently setting up a django backend for a React frontend app. As part of of, I am using django-rest-auth and django-allauth for registration and authentication. I wanted to implement better token management through django-rest-knox. I used the following code to start from and modify my existing app with rest-auth and allauth (which works): https://gist.github.com/AndrewPix/cdd9276b1d5683459b965d5cc4517b26 My problem is the following: When I POST my credentials to the url /rest-auth/login, in the backend a token gets created for the right user, with all the attributes (e.g. expiry date), but I don't get the token and user returned as part of the API call. Instead I receive the below error: AttributeError at /rest-auth/login/ Got AttributeError when attempting to get a value for field token on serializer KnoxSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. Original exception text was: 'str' object has no attribute 'token'. Any help would be greatly appreciated. I think something is wrong with the KnoxSerializer but I can't figure out what? Thanks! AM -
Django URL redirect all PHP requests
How can I redirect all requests containing PHP anywhere in the url? I have this to redirect anything ending with .php url(r'^(?P<path>.*)\.php$', RedirectView.as_view( url='http://www.php.net/', permanent=True)), Now, I want to catch and redirect all url requests containing the keyword php anywhere in the url even without the dot . something like blah/php/blah or blahPHPblah etc. Something like this: url(r'^(?P<path>php*)', RedirectView.as_view( url='http://blah.com/', permanent=True)), If .htaccess rule would be a better solution, I'm open to that as well! -
How to manually populate Django model data for insert
I'm trying to store a list of timings for a speed test. All timings are serialized clientside and sent to the server via ajax. Model: class SpeedTest(models.Model): t1 = models.DecimalField(max_digits=9, decimal_places=6, default=None, blank=True, null=True) t2 = models.DecimalField(max_digits=9, decimal_places=6, default=None, blank=True, null=True) t3 = models.DecimalField(max_digits=9, decimal_places=6, default=None, blank=True, null=True) ... ... ... t100+ = ... View: def save(request): results = json.loads(request.POST.get('results')) speed_test = SpeedTest.objects.create() for result in results: key = "t"+str(result['key']) speed_test.key = value speed_test.save() Where results has the form: results[0]['key'] = 1 results[0]['value'] = 0.539 results[1]['key'] = 2 results[1]['value'] = 0.654 results[2]['key'] = 2 results[2]['value'] = 0.426 ... ... ... results[100+]... I am trying to loop through all the t1 - t100+ values and add them to my model object. I.e a loop to do: speed_test.t1 = 0.539 speed_test.t2 = 0.654 speed_test.t3 = 0.426 ... etc These lines are not doing the job. key = "t"+str(result['key']) speed_test.key = value What is the correct way to do this? -
how to fix this error in cufflinks in jupyter notebook?
I m trying to install cufflinks from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import cufflinks as cf __init__(self, arg, angularaxis, annotations, autosize, bargap, bargroupgap, barmode, barnorm, boxgap, boxgroupgap, boxmode, calendar, colorway, datarevision, direction, dragmode, extendpiecolors, font, geo, grid, height, hiddenlabels, hiddenlabelssrc, hidesources, hoverdistance, hoverlabel, hovermode, images, legend, mapbox, margin, orientation, paper_bgcolor, piecolorway, plot_bgcolor, polar, radialaxis, scene, selectdirection, separators, shapes, showlegend, sliders, spikedistance, template, ternary, title, titlefont, updatemenus, violingap, violingroupgap, violinmode, width, xaxis, yaxis, **kwargs) -
CSRF verification failed ( django-cors-headers) when trying to login to main site from subdomain.
I am developing a web app which has the main site and many subdomains (wildcard). I have used django-cors-headers to add cors headers. I have to log in to the site from a wildcard subdomain. I have read the documentation and did everything listed down there. Still, I am getting a CSRF verification failed. Login from the main domain is working. I am unable to figure out where I am doing wrong. Any help would be appreciated. The code is attached along with this question. html. (This is in the subdomain abc.localhost:8000) {% csrf_token %} ....... settings.py INSTALLED_APPS = [ 'corsheaders', ..... ] MIDDLEWARE = [ ..... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', ...... ] CORS_ORIGIN_ALLOW_ALL = True CORS_REPLACE_HTTPS_REFERER = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( '.localhost:8000', ) CORS_ORIGIN_REGEX_WHITELIST = ( '.localhost:8000', ) CSRF_TRUSTED_ORIGINS = ( '.localhost:8000', ) CSRF_COOKIE_DOMAIN = ( 'localhost:8000', ) -
How to run Django server locally on master branch while I am developing on the other branch
I'm setting up a Django 2.1 server and I want to run the server because it's servicing to my LAN. I want the server to keep running while I'm developing it on the other branch. But the server downs when I change the branch; Actually its branch changes too! How to do that? -
Can a websote and server be developed for streaming video using django/python
I want to make a video streaming server and website , and video traffc analytics tools for that server also. As I am not that familiar with django to make decision to choose the languages, so help me in choosing right language/framework for this purpose. Is django capable/feasible for this purpose. Making video streaming server and developing video analysis tools for that server. -
Foreing key to access data Django
I want to display role_title in template using user_role class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_role = models.ForeignKey(Roles, on_delete=models.CASCADE) def __str__(self): return self.user.username class Roles(models.Model): role_title = models.CharField(max_length=30) role_description = models.CharField(max_length=100) def get_absolute_url(self): return reverse('role-create') def __str__(self) : return self.role_title -
do scheduled Celery task still in progress when the django app will be deployed again
I am new to Scheduling jobs in Django. I am using celery for the asynchronous task. My question is if I have made a task which starts when a user clicks on a button. So my website is running and it has many scheduled task in the background which will be executed at the assigned time. But before their execution, if I will redeploy my app (a new version) to the server again with some changes (not related to the things that celery needs) then will the previous tasks be still in progress or they will be terminated due to environment updation process on the server? I am using Django 2.1 deployment on AWS ElasticBeanstalk using the command line interface to deploy the application. PS: please comment if Question is not clear. -
Query with min and max size in Django rest api
I have this model: class Image(models.Model): image_name=models.CharField(max_length=30) image=models.ImageField(upload_to='images',width_field='image_width', height_field='image_height',) image_width=models.PositiveIntegerField(null=True, blank=True, editable=False) image_height=models.PositiveIntegerField(null=True, blank=True, editable=False) image_size=models.IntegerField(null=True, blank=True,editable=False) I am able to save the images with all these attributes. I want to have a query like this to return all the images with height greater than 100 and less than 300: GET /images/?minheight=100&maxheight=300 How to achieve this in Django?