Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to make family relations
I wonder how can we make a relations between 2 users, which can be applied in reverse. The goal is when creating an object via django admin to add relation between 2 users and create the opposite of it in the second user, the sex of the user is very important for the reverse connection. I have tried to create the reverse of it when creating the object but then it crashes because it tries to recreate the object again and again. models.py SEX = ( ('m', 'Male'), ('f', 'Female'), ) class User(models.Model): first_name = models.CharField(max_length=30, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) sex = models.CharField(max_length=1, choices=SEX) def __str__(self): return f"{self.first_name} {self.last_name}" RELATIONS = ( ('mother', 'Mother'), ('daughter', 'Daughter'), ('father', 'Father'), ('son', 'Son') ) RELATIONS_REVERSE = { 'mother':{ 'm':'son', 'f':'daughter' }, 'father':{ 'm':'son', 'f':'daughter' }, 'son':{ 'm':'father', 'f':'daughter' }, 'daughter':{ 'm':'father', 'f':'mother' } } class UserRelation(models.Model): User_1 = models.ForeignKey(User, related_name="User_1", null=False, blank=False, on_delete=models.CASCADE) User_2 = models.ForeignKey(User, related_name="User_2", null=False, blank=False,on_delete=models.CASCADE) relation = models.CharField(max_length=30, choices=RELATIONS, null=False, blank=False) #THIS DOES NOT WORK! # def save(self): # UserRelation.objects.create( # User_1= self.User_2, # User_2= self.User_1, # relation= RELATIONS_REVERSE[str(self.relation)][self.User_2.sex] # ) admin.py from django.contrib import admin # Register your models here. from .models import User, UserRelation … -
Django: Problem with Understanding Super Save Function
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. Right now, I am facing a problem understanding this code: def save(self): super(Review, self).save() self.slug = '%i-%s' % ( self.id, slugify(self.game.title) ) super(Review, self).save() It comes from models.py: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Tag(models.Model): label = models.CharField(max_length=20) def __str__(self): return self.label class Game(models.Model): title = models.CharField(max_length=100) developer = models.CharField(max_length=100) platform = models.CharField(max_length=50, default='null') label_tag = models.ManyToManyField(Tag) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Review(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) review = models.CharField(max_length=1000) date = models.DateField(auto_now=True) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.review def save(self): super(Review, self).save() self.slug = '%i-%s' % ( self.id, slugify(self.game.title) ) super(Review, self).save() It looks like the save function is saving the slug. But I don't understand it completely. Does it converting integer to string? What is super doing here? Would you please give me a complete explanation about the save function? -
Django validation error messages only showing in admin page
I have a SignUp form that interacts with Django's user model to create new users. If both password fields are different, the user is not created, so I guess validation is working. But somehow, a validation error message is not shown, the form page is just rendered again. When I go to Django's admin page, the error messages pop up there! Why is it not popping in my template?! This is my form: class SignUpForm(forms.ModelForm): password = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'placeholder':'Password', 'class':'form-control', 'type':'password'}),) password2 = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'placeholder':'Confirm Password', 'class':'form-control', 'type':'password'}),) class Meta: model = User widgets = {'first_name': forms.TextInput(attrs={'placeholder':'First Name', 'class':'form-control'}), 'last_name': forms.TextInput(attrs={'placeholder':'Last Name', 'class':'form-control'}), 'email': forms.TextInput(attrs={'placeholder':'Email', 'class':'form-control', 'type':'email'}), 'username': forms.TextInput(attrs={'placeholder':'Username', 'class':'form-control'}), 'password': forms.TextInput(attrs={'placeholder':'Password', 'class':'form-control', 'type':'password'}) } fields = {'first_name', 'last_name', 'email', 'username', 'password'} def clean(self): cleaned_data = super(SignUpForm, self).clean() password = cleaned_data.get('password') password2 = cleaned_data.get('password2') if password != password2: raise forms.ValidationError('Passwords do not match!') And this is my view: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) form.save() user = authenticate(username=username, password=password) login(request, user) messages.add_message(request, messages.SUCCESS, 'Account created successfully!') return HttpResponseRedirect('/') else: messages.add_message(request, messages.ERROR, "There's an error in the form! Please fill it again.") return render(request, … -
Django admin download data as csv
I want to download data from django admin as .csv file. I followed tutorial https://www.endpoint.com/blog/2012/02/22/dowloading-csv-file-with-from-django. I didn't see download csv option. How can I solve my problem? I am using Python3, migration created. This is my code models.py from django.db import models from django.contrib import admin class Stat(models.Model): code = models.CharField(max_length=100) country = models.CharField(max_length=100) ip = models.CharField(max_length=100) url = models.CharField(max_length=100) count = models.IntegerField() class StatAdmin(admin.ModelAdmin): list_display = ('code', 'country', 'ip', 'url', 'count') def download_csv(self, request, queryset): import csv f = open('some.csv', 'wb') writer = csv.writer(f) writer.writerow(["code", "country", "ip", "url", "count"]) for s in queryset: writer.writerow([s.code, s.country, s.ip, s.url, s.count]) admin.site.register(Stat, StatAdmin) -
Developing a dashboard using Django?
Apologies in advance as this question is quite broad. My overall goal is to create a web application that allows for interactive analysis of NOAA model output data. For now, let's say the project will consist of two different dashboards: The first dashboard will take current output model data from NOAA based on user inputs (e.g., location) and display the data using interactive plotly plots. The second dashboard will be for displaying historical data from archived NOAA data. My background is more in chemistry and science, so while I have a good understanding of data analysis packages like Pandas, I'm much newer to web dev tools such as Django. I was originally able to create my two dashboards using Plotly Dash. I saved some sample data to my local computer and used Pandas to select subsets of data that were then plotted with plotly. However, I'd like to scale this to a fully-functioning webpage and therefore need to migrate this project to a Django framework. This is where I need help. Basically I'm trying to determine how the big-picture flow of this project would need to look. For example, below I give the workflow for a specific example in which … -
Django-cms Content Creation Wizards Custom Text Editor Implementation
I am learning Django-CMS and now I am trying to add content creation wizards. Currently, it is working nice but the problem is: it doesn't have a rich text editor. I am not getting how to implement this in content creation wizards. This is models.py : class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=500) this is my forms.py file class PostForm(ModelForm): class Meta: model = Post fields = ['title', 'content',] exclude = [] and this is my cms_wizers.py file: from cms.wizards.wizard_base import Wizard from cms.wizards.wizard_pool import wizard_pool from blog.forms import PostForm class BlogWizard(Wizard): pass blog_wizard = BlogWizard( title="Create Content", weight=200, form=PostForm, description="Create a new Content", ) wizard_pool.register(blog_wizard) Can anyone help me to implement rich text editor here? I know Django-cms uses CKEditor in page creation but I am not getting how to bring/implement this in my content creation wizards. It would be much appreciated if anyone can help me to implement this. -
Creating youtube playlist with python
i had implemented the following code from the google docs ... -- coding: utf-8 -- Sample Python code for youtube.playlists.insert See instructions for running these code samples locally: https://developers.google.com/explorer-help/guides/code_samples#python import os import google_auth_oauthlib.flow import googleapiclient.discovery import googleapiclient.errors scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"] def main(): Disable OAuthlib's HTTPS verification when running locally. DO NOT leave this option enabled in production. os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" api_service_name = "youtube" api_version = "v3" client_secrets_file = "YOUR_CLIENT_SECRET_FILE.json" Get credentials and create an API client flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file( client_secrets_file, scopes) credentials = flow.run_console() youtube = googleapiclient.discovery.build( api_service_name, api_version, credentials=credentials) request = youtube.playlists().insert( part="snippet,status", body={ "snippet": { "title": "Sample playlist created via API", "description": "This is a sample playlist description.", "tags": [ "sample playlist", "API call" ], "defaultLanguage": "en" }, "status": { "privacyStatus": "private" } } ) response = request.execute() print(response) if name == "main": main() after going to the link, they were asking for some authorization code...... this error is coming whats the issue... ERROR: redirect_uri_mismatch..... -
XML Parse error django-saml2-auth SSO when trying to authenticate through okta
This error started after rebuilding my docker container with the same compose file and dockerfile. Nothing has changed. django_gunicorn | Internal Server Error: /saml2_auth/acs/ django_gunicorn | Traceback (most recent call last): django_gunicorn | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner django_gunicorn | response = get_response(request) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response django_gunicorn | response = self.process_exception_by_middleware(e, request) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response django_gunicorn | response = wrapped_callback(request, *callback_args, **callback_kwargs) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view django_gunicorn | return view_func(*args, **kwargs) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/django_saml2_auth/views.py", line 159, in acs django_gunicorn | resp, entity.BINDING_HTTP_POST) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/client_base.py", line 714, in parse_authn_request_response django_gunicorn | binding, **kwargs) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/entity.py", line 1194, in _parse_response django_gunicorn | response = response.verify(keys) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/response.py", line 1051, in verify django_gunicorn | if self.parse_assertion(keys): django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/response.py", line 937, in parse_assertion django_gunicorn | if not self._assertion(assertion, False): django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/response.py", line 817, in _assertion django_gunicorn | if not self.condition_ok(): django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/response.py", line 616, in condition_ok django_gunicorn | raise Exception("Not for me!!!") django_gunicorn | Exception: Not for me!!!``` -
Django rest framework raw queries select not working
I want to use a raw query in order to make a JOIN in a many to many relationship, and show it in the Django Rest Framework. But the "SELECT" part of the query is not working, and it shows whatever the serializer has in "fields" and thus the JOIN is also not working. serializers.py: class UserTestSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" views.py: class UserTestQuery(viewsets.ModelViewSet): queryset = User.objects.raw('SELECT * ' + 'FROM users_user ' + 'INNER JOIN sysadmin_works_as ON users_user.user_id = sysadmin_works_as.employee_id;') serializer_class = UserTestSerializer I want to show a join in the API with these 3 models, so I must use raw SQL. Why is it not working? And the models I'm using are: class User(AbstractUser): first_name = None last_name = None username = None user_id = models.AutoField(primary_key=True) email = models.EmailField(_('email address'), unique=True) national_id_number = models.CharField(max_length=30) f_name = models.CharField(max_length=100) l_name = models.CharField(max_length=100) star_count = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True,null=True) is_superuser = models.BooleanField(default = False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now=True,null=True) deleted_at = models.DateTimeField(blank = True, null=True) date_joined = models.DateTimeField(auto_now_add=True,null=True) app_role = models.ForeignKey(App_roles,related_name='employee',on_delete=models.SET_NULL,blank=True,null=True) #Un Rol_de_Aplicacion le pertenece a muchos usuar class Works_as(models.Model): work_id = models.AutoField(primary_key=True) started_at = models.DateTimeField(auto_now_add=True) updates_at = models.DateTimeField(auto_now=True) r_created_at = models.DateTimeField(auto_now_add=True) r_updated_at … -
Django: Problem with Understanding Objects in For Loop
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have managed to do some protion of the app. Right now, I am a bit confused with a line of code. I have a code like this in one of my template files: {% extends 'gamereview/base.html' %} {% block title%} Detail {% endblock %} {% block content %} <h3>This is the review for {{game.title}} </h3> <ul>{% for review_item in game.review_set.all %} <li>{{ review_item.review }}</li> {% endfor %} </ul> {% endblock %} I don't understand this portion: <ul>{% for review_item in game.review_set.all %} What does this line mean? Here are the codes in models.py: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Tag(models.Model): label = models.CharField(max_length=20) def __str__(self): return self.label class Game(models.Model): title = models.CharField(max_length=100) developer = models.CharField(max_length=100) platform = models.CharField(max_length=50, default='null') label_tag = models.ManyToManyField(Tag) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Review(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) review = models.CharField(max_length=1000) date = models.DateField(auto_now=True) slug = models.SlugField(max_length=150, default='null') … -
Django count in annotation
I have a profile model with a ManyToMany field called that relates to a Stock. In my admin dashboard I'm trying to show the number of watchlists each stock is in. The annotation query I have is: return qs.annotate(watchlist_count=Count('profile__watchlist__symbol', distinct=True)) But it's returning incorrect results Here are the models: class Profile(models.Model): user = OneToOneField(User, on_delete=models.CASCADE) watchlist = ManyToManyField(Stock, blank=True) def __str__(self): return self.user.email class Stock(models.Model): symbol = CharField(max_length=15, unique=True) name = CharField(max_length=100) category = CharField(max_length=30, choices=CATEGORY_CHOICES, blank=True) about = TextField(help_text='About this company') def __str__(self): return f'{self.symbol} - {self.name}' What is wrong with my annotation query? -
Rename Model from app A that is used as a superclass in app B
I have a class in one app (we'll call app A) that I need to rename from FirstName to SecondName. class FirstName(models.Model): pass # stuff In app B, I import this class to use as a base for another model. from first_app.models import FirstName class ProxyModel(FirstName): pass # stuff What I did is update the model name and all references to it. class SecondName(models.Model): pass # stuff class ProxyModel(SecondName): pass # stuff operations = [ migrations.RenameModel( old_name='FirstName', new_name='SecondName', ), ] When I run makemigrations I get an error: django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'app_b.ProxyModel'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) in an app with no migrations; It seems I cannot import the renamed base model before migration, but I cannot migrate until I resolve the base class issue... I did already try using the previous model name for the Proxy base class, but get model not found error. I also tried to comment out the proxy model, but still got the error (I think because of the migrations already run for that proxy model). How can I get around this rename dependency loop? Python 2.7, Django 1.11 -
Angular 6 cannot download pdf with greek characters from Django 2.2?
I am using Angular 6 and Django 2.2 and Ι am trying to request a pdf containing greek chars. here is my angular side code: service: getUserGuide() { return this._httpClient.post("association-rules/user-guide/", { headers: new HttpHeaders({ 'Content-Type': 'application/pdf', 'Accept' : 'application/pdf' }), responseType: 'blob', }) } component: getUserGuide() { this._targetProductService.getUserGuide() .subscribe( (response: any) => { var blob = new Blob([response], { type: 'application/pdf' }); saveAs(blob, 'report.pdf'); }); } Here is my django side code: class user_guide_view(APIView): permision_classes= [IsAuthenticated] def post(self, request): try: requestedFile= 'user_guide.pdf' folder= 'services_static_files/association_rules/' with open(folder+'/'+requestedFile, 'r', encoding="ISO-8859-1") as myfile: response = HttpResponse(myfile, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.pdf' return response except (IOError,KeyError): return HttpResponse('no such file', status=status.HTTP_404_NOT_FOUND) Here you can see my request: It is obvious that: 'Content-Type' & 'Accept' of the request headers are wrong 'Content-Type' of response headers is right What I have done: After several suggested workarounds I came across online, I have tried combinations such as: responseType: 'blob', responseType: 'blob' as 'blob', responseType: 'blob' as 'json', responseType: ResponseContentType.Blob by adjusting the headers accordingly. Question 1 Why I cannot set properly ('Content-Type'-> 'application/pdf' and 'Accept'-> 'application/pdf') -
dynamic prices in django-oscar
I was looking how to implement dynamic prices (based on amount in basket, in my case) in my django-oscar e-shop. In the source of AbstractStockRecord (see here), I read about the price field: It is NULLable because some items don't have a fixed price but require a runtime calculation. So it seems possible, but how? Strategies and policies ahead, I dont really know where to start (also, the dynamic price calculation would happen before tax/strategy, etc..?) Any insights were to hook in or whater welcome! -
Django celery thows error when I import django model or function using one
I have a problem with the configuration of celery with django. When I attempt to import function like this into the celery file: def add_proxy(): proxy = ProxyList(timezone.now()) proxy.save() running command: celery -A estatefilter_backend worker -l info causes error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I'm using python 3.7.5 and django 2.2.7 -
Serializer field for integer or string
I want to have serializer with field which can take integer(not floats or any other numeric type!) or string as an input.Is there any way to make it better/more pretty? class MyField(Field): def to_representation(self, value): if isinstance(value, int): return value elif isinstance(value, str): return value else: raise ValidationError('Error') def to_internal_value(self, data): if isinstance(data, int): return data elif isinstance(data, str): return data else: raise ValidationError('Error') class MySerializer(Serializer): my_field = MyField() -
Authtoken migration not working despite unit test functioning
I'm adding TokenAuthentication to our django project. All was going well, and I've added a migration and unit test for the token auth: # Migration from django.db import migrations def create_missing_tokens(apps, schema_editor): """ Tokens were added in 0002_auto_20160226_1747, we thus need to populate the tokens table for existing users """ Token = apps.get_model('authtoken', 'Token') User = apps.get_model('accounts', 'CustomUser') for user in User.objects.all(): Token.objects.get_or_create(user=user) class Migration(migrations.Migration): dependencies = [ # depends on authtoken migration ('accounts', '0003_subscription_max_updates_per_day'), ('authtoken', '0002_auto_20160226_1747'), # latest migration in the authtoken package ] operations = [ migrations.RunPython(create_missing_tokens, reverse_code=migrations.RunPython.noop), ] # unit test class MigrationTestCase(TransactionTestCase): '''A Test case for testing migrations''' # These must be defined by subclasses. migrate_from = None migrate_to = None def setUp(self): super(MigrationTestCase, self).setUp() self.executor = MigrationExecutor(connection) self.executor.migrate(self.migrate_from) def migrate_to_dest(self): self.executor.loader.build_graph() # reload. self.executor.migrate(self.migrate_to) @property def old_apps(self): return self.executor.loader.project_state(self.migrate_from).apps @property def new_apps(self): return self.executor.loader.project_state(self.migrate_to).apps from accounts.models import CustomUserManager class SummaryTestCase(MigrationTestCase): """ We need to test that data is populated in the summary field on running the migration """ migrate_from = [('accounts', '0003_subscription_max_updates_per_day')] migrate_to = [('accounts', '0004_create_tokens')] def setup_before_migration(self): manager = CustomUserManager() User = self.old_apps.get_model('accounts', 'CustomUser') manager.model = User manager.create_user(email='contact@a.fr', # nosec password='kjnfrkj', ) def test_token_populated(self): # runs setup self.setup_before_migration() # now migrate self.migrate_to_dest() # grab … -
Django - Get a single timestamp per foreign key ID (MySQL)
Im having trouble getting only a single record per foreign key ID on the below model, I have tried this query, but it doesnt seem to be doing anything at all currently Query: queryset = BGPData.objects.annotate(max_timestamp=Max('timestamp')).filter(timestamp=F('max_timestamp')).select_related( 'device_circuit_subnet__subnet', 'device_circuit_subnet__device', 'device_circuit_subnet__circuit', 'device_circuit_subnet__device__site', ) Model: class BGPData(models.Model): device_circuit_subnet = models.ForeignKey(DeviceCircuitSubnets, verbose_name="Device", on_delete=models.CASCADE) bgp_peer_as = models.CharField(max_length=20, verbose_name='BGP Peer AS', blank=True, null=True) bgp_session = models.CharField(max_length=10, verbose_name='BGP Session', blank=True, null=True) bgp_routes = models.CharField(max_length=10, verbose_name='BGP Routes Received', blank=True, null=True) service_status = models.CharField(max_length=10, verbose_name='Service Status', blank=True, null=True) timestamp = models.DateTimeField(auto_now=True, blank=True, null=True) Sample Data im testing with (printed as a dict), there should only be one record for "device_circuit_subnet_id" : "10", the one which is newest. ive read that distinct is used for this but were running MySQL, is there another way? Thanks [{ "id": 4, "device_circuit_subnet_id" : "10", "hostname": "EDGE", "circuit_name": "MPLS", "subnet": "172.1.1.1", "subnet_mask": "/30", "bgp_session": "1w2d", "bgp_routes": "377", "bgp_peer_as": "1", "service_status": "Up", "timestamp": "2019-11-18 16:16:17" }, { "id": 5, "device_circuit_subnet_id" : "11", "hostname": "INT-GW", "subnet": "1.1.1.1", "subnet_mask": "/24", "bgp_session": null, "bgp_routes": null, "bgp_peer_as": null, "service_status": "unknown", "timestamp": "2019-08-07 14:46:00" }, { "id": 8, "hostname": "EDGE", "device_circuit_subnet_id" : "20", "circuit_name": "MPLS 02", "subnet": "172.2.1.1", "subnet_mask": "/30", "bgp_session": null, "bgp_routes": null, "bgp_peer_as": null, "service_status": "unknown", "timestamp": "2019-11-15 … -
Is there a way to inject a featured image field in mezzanine / django RichTextPage model?
Is there a way to inject a featured image field in Mezzanine / Django RichTextPage's model? I need get a image, to specific pages in "richtextpage.html" template, but these are different from blogPost models that have a featured image field. -
django app architecture: multithreading or correct processing of background tasks
Wrote a django application to control the launch of queries in the background. According to server events, for example, post_save tasks are created or updated for execution in the background (apsheduler background tasks). While developing on the local machine, everything was fine - django provided the functionality of simultaneously connecting and fulfilling long tasks for different clients without freezes. However, when moving to production, the server using the gunicorn encountered such a problem that a request is being made from one client, while others are waiting. Set up several workers (2 * CPU) +1), but another problem appeared: When django is started with several workers, then each instance of django (worker) starts its background task (which needs to be done only once). And instead of just one, as many tasks are run as there are workers. Performance of tasks is critical for my application, and simultaneous execution of requests from different clients so far is in second place. Therefore set the parameter number of workers: 1. But I understand that this is a compromise, and that I’m doing something wrong. How correct is this task should be architecturally solved? The problem, it seems to me, is complicated by the fact … -
Is it necessary to specify default=django.utils.timezone.now while creating automatic primary key field for Django model
I created model Class Team(models.Model): team = models.IntegerField(primary_key = True) name = models.CharField(max_length = 30) After it i saved some objects from this model and decided to change manually created primary key field to auto primary key field. I changed previously created model to Class Team(models.Model): team = models.IntegerField(null=True) name = models.CharField(max_length = 30) After it i run python manage.py makemigrations Django promted that i need specify default=django.utils.timezone.now here is my question what reason to specify this field with django.utils.timezone.now Why i can create primary key field without specifying it? What if i delete default=django.utils.timezone.now from migrations file and will migrate it ? -
How to setup SSH connection with Django
I want to setup SSH connection with Django. Run shell commands and display results on the User Interface. -
Python click project, "Django is not available on the PYTHONPATH " error
I am having a click project which don't use/need Django anywhere but while running prospector as part of static analysis throws this strange error Command prospector -I __init__.py --strictness veryhigh --max-line-length 120 src/ Error Line: 1 pylint: django-not-available / Django is not available on the PYTHONPATH There was no reference of django anywhere in the project/code . I am fairly new to python, Am i missing something obivious here ? python-version : 3.7 pip list apipkg 1.5 asn1crypto 1.2.0 astroid 2.3.2 atomicwrites 1.3.0 attrs 19.3.0 auger-python 0.1.35 bitmath 1.3.3.1 boto3 1.10.14 botocore 1.13.14 bravado 9.2.0 bravado-core 4.9.1 certifi 2019.9.11 cffi 1.13.2 chardet 3.0.4 click 6.7 colorama 0.4.1 coloredlogs 10.0 coverage 4.5.4 cryptography 2.3.1 deb-pkg-tools 4.5 docutils 0.15.2 dodgy 0.1.9 entrypoints 0.3 execnet 1.7.1 executor 21.3 fasteners 0.15 filelock 3.0.12 flake8 3.7.9 flake8-polyfill 1.0.2 funcsigs 1.0.2 future 0.18.2 humanfriendly 4.18 hvac 0.7.1 idna 2.5 importlib-metadata 0.23 isort 4.3.21 jmespath 0.9.4 jsonpointer 2.0 jsonschema 3.1.1 lazy-object-proxy 1.4.3 mando 0.6.4 mccabe 0.6.1 mock 3.0.5 monotonic 1.5 more-itertools 7.2.0 murl 0.5.1 packaging 19.2 pep8 1.7.1 pep8-naming 0.4.1 pip 19.3.1 pluggy 0.13.0 property-manager 2.3.1 prospector 1.1.7 py 1.8.0 pycodestyle 2.5.0 pycparser 2.19 pydocstyle 4.0.1 pyflakes 2.1.1 pylint 2.4.3 pylint-celery 0.3 pylint-django 2.0.10 pylint-flask 0.6 pylint-plugin-utils … -
Django allauth login / signup/ or any links is not showing the template
I'm using Django all-auth for authentication, after the setup, I'm trying "http://127.0.0.1:8000/accounts/login/" link to test the login but the template is not rendering. The whole page is blank and the HTML is showing my 'base.html's extended version. I'm not sure where is the problem. I'm using virtual env as well. Though I believe something wrong with the template rendering. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainapp', # Thrid party apps 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] SITE_ID = 1 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('mainapp.urls')), ] NOTE: this is not the first time I'm using Django all-auth and I've not such kind of problem before. -
Django ValidationError CSV-Upload
I am trying to upload a CSV file into my Django model. Although the upload of the data works fine (all the rows get copied into the database), at the end Django returns a ValidationError ["'' value must be a decimal number."] error message. From the local vars section of the error message I kind of get the reason - when the iteration reaches the end of the rows contianing data, there is obviously no decimal number. So django throws an error. However, I do not understand why as there is always a last row after which there is no more data. experimneted a bit to try to find the problem: I think that worked is so copy the whole data from the original CSV into a new SCV - suddenly everything works fine and no error message appears. I would love to accomplish this with the original CSV file and no error message! Would appreciate any help. My CSV files are CSV UTF-8 and they are saved in Excel models.py from django.db import models class Testdata3(models.Model): key = models.CharField(max_length=100, primary_key=True) assetclass = models.CharField(max_length=25) value = models.DecimalField(max_digits=25,decimal_places=10) performance = models.DecimalField(max_digits=25,decimal_places=10) def __str__(self): return self.key views.py from django.shortcuts import render from …