Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST + filter/ Combining data on field X in django as an embedded response
iam use DJango Rest + Filter and now i have this api response { "symbol": "ZERO", "costs": "6.1391", "timestamp": "2020-04-08T14:15:55.765835Z" }, { "symbol": "ZERO", "costs": "6.1892", "timestamp": "2020-04-08T14:15:01.775659Z" }, { "symbol": "ZERO", "costs": "6.1221", "timestamp": "2020-04-08T14:13:49.217715Z" }, As you can see. I want to combine the timestamp and costs into an embedded response. To make it this way. That is, given the costs and timestamp for the every coin: {"symbol":"ZERO","costs":[ {"timestamp":"2019-12-14T00:00:07+00:00", "price":5.9505181}, {"timestamp":"2019-13-14T00:00:07+00:00", "price":5.915181}, {"timestamp":"2019-14-14T00:00:07+00:00", "price":6.915181} ]} serializers.py class CoinCostsSerializer(serializers.ModelSerializer): symbol = serializers.ReadOnlyField(source='coin_id.symbol') costs = serializers.CharField(source='price') class Meta: fields = ('symbol', 'costs', 'timestamp') model = CoinCosts views.py class CoinCostFilterSet(filters.FilterSet): class Meta: model = CoinCosts fields = { 'coin_id__symbol': ['exact'], 'timestamp': ['gt', 'lt'], } class CoinCostViewSet(viewsets.ModelViewSet): queryset = CoinCosts.objects.all() serializer_class = CoinCostsSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = CoinCostFilterSet How to do it? Thanks! -
How to change a Django model field argument dynamically
Given the model class Payments(models.Model): is_valid = models.BooleanField(blank=True) customer = models.ForeignKey('Customer', on_delete=models.CASCADE) ..... How can I add, remove and change the model field argument blank dynamically in my code ? I am writing unit tests (pytest) for a model heavy project, and want to remove the cumbersome effort of creating a mock record (more records if record has a foreign key) with many fields when only one or two are relevant for the test. -
How can I have a database with thousands of tables with varying number of columns that are all of the same class in Django / SQLAlchemy ORM?
I have financial statement data on thousands of different companies. Some of the companies have data only for 2019, but for some I have decade long data. Each company financial statement have its own table structured as follows with columns in bold: lineitem---2019---2018---2017 2...............1000....800.....600 3206...........700....300....-200 56.................50....100.....100 200...........1200......90.....700 This structure is preferred over more of a flat file structure like lineitem-year-amount since one query gives me the correct structure of the output for a financial statement table. lineitem is a foreignkey linking to the primary key of a mapping table with over 10,000 records. 3206 can for example mean "Debt to credit instituions". I also have a companyIndex table which has the company ID, company name, and table name. I am able to get the data into the database and make queries using sqlite3 in python, but advanced queries is somewhat of a challenge at times, not to mention that it can take a lot of time and not be very readable. I like the potential of using ORM in Django or SQLAlchemy. The ORM in SQLAlchemy seems to want me to know the name of the table I am about to create and want me to know how many columns … -
Django Admin display sum of column values
Is it possible to somewhere in the admin interface sum the values of a column and show it something like this: It doesn't need to be in the label, as that seems to be very complicated to achieve. Any other place that wouldn't require to get another column is good. I am using Django 2.2.7 I tried two plugable apps, Django-admin-totals and totalsum app. They didn't work at all. -
Having trouble to get python work with Mysql and Google Cloud
I'm having trouble installing and connecting mysql to python/django. It feels like i have tried everything from downloading through pip or installer package. I always seem to get the same error message. Or something similar. Collecting mysql-python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip Building wheels for collected packages: mysql-python Building wheel for mysql-python (setup.py) ... error Complete output from command C:\Users\JensNymoen\PycharmProjects\Shipmanager\venv\Scripts\python.exe -u -c "import setuptools, tokenize;file='C:\Users\JensNymoen\AppData\Local\Temp\pip-install-3c7pto5d\mysql-python\setup.py';f=getattr(tokenize, 'open' , open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" bdist_wheel -d C:\Users\JensNymoen\AppData\Local\Temp\pip-wheel-rj6h57pe --python-tag cp38: running bdist_wheel running build running build_py creating build creating build\lib.win32-3.8 copying _mysql_exceptions.py -> build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb__init__.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building '_mysql' extension creating build\temp.win32-3.8 creating build\temp.win32-3.8\Release C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\includ e" -IC:\Users\JensNymoen\PycharmProjects\Shipmanager\venv\include -IC:\Users\JensNymoen\AppData\Local\Programs\Python\Python38-32\include -IC:\Users\JensNymoen\AppData\Local\Programs\Python\Python38-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\ BuildTools\VC\Tools\MSVC\14.25.28610\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC:\Program F iles (x86)\Windows Kits\10\include\10.0.18362.0\um" … -
Conda environment.yml without Conda
Currently i am trying to dockerize an django app that the last developer used conda to develop. And the required libs are listed in a file called environment.txt . Is it possible to install the dependencies without having conda installed since i dont want to add conda in my app stack ? I've read that you cant just copy and paste the dependencies into a requirements.txt file and install it with pip because that would install a lot of conda dependencies together, is this right ? -
Private RSS Mp3 Feed in Django with many Querys
For our Website we want to create an RSS Feed for Mp3 Files. So far so good. This Website has authentification and every single User had bought different items. This means, that I need to create an RSS Feed for every single user. And it has to be dynamic. When someone buys a new item, the RSS Feed should automatically add this item. I don't have a clue how to build this. It would be great if you can tell me if this is even possible :) All the best and stay healthy! -
Django formtools, how to edit database stored data?
I am using django formtools in a project. So far I can show/skip the individual forms and save all the information to the database. The problem is that I need users to be able to edit the submitted information. Right now I am able to retrieve the information from the database and fill the initial_dict of the wizard. Thus, if users travel all the steps in the wizard, they can edit the information and save the changes. The problem is that for this to work users need to travel all the steps in the wizard in order to move the information from initial_dict to the storage of the wizard. So my questions are: 1.- How do I set up the wizard so users can edit the information without having to travel all the steps? I guess this is a rather common situation so perhaps I am missing something and there is a simple solution. 2.- If I have to manually set up the storage of the wizard, what do I have to keep in mind? -
Django storing a repository of files
I am working on a "repository manager", basically I have 3 models: Dataset File Author (can be the author of a file or one of the authors of a dataset) Author class Author(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) email = models.EmailField() phone = models.CharField(max_length=20, blank=True) class Meta: unique_together = (("name", "surname", "email"),) Dataset class Dataset(models.Model): token = models.CharField(max_length=300, unique=True) name = models.CharField(max_length=150, unique=True) description = models.TextField(blank=True) slug = models.SlugField(max_length=200, blank=True, unique=True) authors = models.ManyToManyField(Author, related_name='author') remote = models.URLField(max_length=300) File class File(models.Model): creator = models.ForeignKey(Author, related_name='creator', null=True, on_delete=models.SET_NULL) dataset = models.ForeignKey(Dataset, related_name='dataset', on_delete=models.CASCADE) path = models.CharField(max_length=200, default="", blank=True, null=True) name = models.CharField(max_length=100) description = models.CharField(max_length=300, blank=True) url = models.URLField(max_length=300) So I have a Dataset that is owned by one or more Author that is composed of many File. While Datasets and Authors creation/updating is working well, I am facing some difficulties in handling Files and in particular adding/removing files. At the moment I have managed to write an API that deletes all files and allows us to 're-upload' the entire set of files of the dataset. But I would prefer allowing only partial updates/insertion. Here my serializers: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('name', 'surname', 'email', 'phone') … -
Is there a way to select specific fields from model in django?
Is there a way to select some specific fields from model with Foreign Key. Here is an example: let's say I have class Product(models.Model): CATEGORY = ( ('A', 'A'), ('B', 'B'), ('C', 'C'), ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Work Under Progress', 'Work Under Progress'), ('Delivered', 'Delivered'), ) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return self.product.name The purpose is to get the product name and product price in the order class. Is there any way to do so? (I'm very new to Django and could find exactly this in the doc) Thanks -
Replace the filter field name in URL with the foreign key in Django REST
I use Django REST Filters. I need replace in URL /CoinCost/?coin_id__symbol=ZERO to /CoinCost/?symbol=ZERO coin_id__symbol to symbol. coin_id is the ForeignKey Field symbol (see models.py) views.py class CoinCostFilterSet(filters.FilterSet): class Meta: model = CoinCosts fields = { 'coin_id__symbol': ['exact'], 'timestamp': ['gt', 'lt'], } class CoinCostViewSet(viewsets.ModelViewSet): symbol = CoinSerializer queryset = CoinCosts.objects.all() serializer_class = CoinCostsSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = CoinCostFilterSet serializers.py class CoinCostsSerializer(serializers.ModelSerializer): symbol = serializers.ReadOnlyField(source='coin_id.symbol') initialReserve = serializers.CharField(source='reserve') costs = serializers.CharField(source='price') class Meta: fields = ('symbol', 'crr', 'volume', 'initialReserve', 'costs', 'timestamp') model = CoinCosts models.py class Coins(models.Model): name = models.CharField(max_length=150) symbol = models.CharField(max_length=45) crr = models.CharField(max_length=3) class CoinCosts(models.Model): coin_id = models.ForeignKey(Coins, on_delete=models.CASCADE) crr = models.CharField(max_length=3) volume = models.DecimalField(max_digits=19, decimal_places=4) reserve = models.DecimalField(max_digits=19, decimal_places=4) price = models.DecimalField(max_digits=19, decimal_places=4) timestamp = models.DateTimeField(auto_now_add=True, blank=True) i testing this : class CoinCostFilterSet(filters.FilterSet): symbol = django_filters.ModelChoiceFilter(field_name='coin_id__symbol', to_field_name='symbol', queryset=Coins.objects.all()) class Meta: model = CoinCosts fields = { 'symbol': ['exact'], 'timestamp': ['gt', 'lt'], } class CoinCostViewSet(viewsets.ModelViewSet): symbol = CoinSerializer queryset = CoinCosts.objects.all() serializer_class = CoinCostsSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = CoinCostFilterSet But Result: no work. White page. 0 results.. and status 200 Please Help! Thanks! -
is there any way to display jupyter notebooks with django
I am really new on these things and i want to create a blog that i can publish my data notes and other articles. I want to learn if there is any way to display my jupyter notebooks or (.pdf, .docx, etc.) files directly on my website? I am already appreciate for your advice and answers. Thanks. -
Django served with WAMP blocking outbound requests
I am currently serving a simple django application via the runserver command on a windows machine. The application is a simple html page that will do a simple webscrape when a button is pressed. It works fine until I attempt to serve it via WAMP with mod_wsgi. Then, running the application returns this error when I click the button to do the scrape: [wsgi:error] [pid 8336:tid 1192] [client (ipaddress)] https://www.python.org\r, referer: (ipaddress)/simpleapp Is there an additional setting for WAMP that I have to do in order to webscrape? -
How to let Django know when to Insert or Update with overrided save()
I want to do some piece of code when my model inserts, and when it updates another piece of code. I have this model with an overrided save() method. The idea is to execute that code only for insert. How can I tell django when to insert, when to update and what code to execute for each one? class Galeria(models.Model): galeriaid = models.AutoField(db_column='GaleriaID', primary_key=True) nombre = models.CharField(db_column='Nombre', max_length=128, blank=True, null=True) ruta = models.FileField(db_column='Ruta', max_length=512, blank=True, null=True) def save( self, force_insert=False, force_update=False, *args, **kwargs): super( Galeria, self ).save( *args, **kwargs ) ruta = self.ruta if ruta: oldfile = self.ruta.name dot = oldfile.rfind( '.' ) newfile = str( self.pk ) + oldfile[dot:] if newfile != oldfile: self.ruta.storage.delete( newfile ) if newfile.endswith(".jpg"): self.ruta.storage.save( "imagenes/" + str(timezone.now().strftime("%Y/%m/")) + str(newfile), ruta ) self.ruta.name = "imagenes/" + str(timezone.now().strftime("%Y/%m/")) + str(newfile) elif newfile.endswith(".mp4"): self.ruta.storage.save( "videos/" + str(timezone.now().strftime("%Y/%m/")) + str(newfile), ruta ) self.ruta.name = "videos/" + str(timezone.now().strftime("%Y/%m/")) + str(newfile) else: self.ruta.storage.save( newfile, ruta ) self.ruta.name = newfile self.ruta.close() self.ruta.storage.delete( oldfile ) super( Galeria, self ).save( *args, **kwargs ) -
Wagtail CMS +CRM
Tell me please, Can I connect a CRM system to wagtailCMS?? How can I do that? What technologies can be used for this? I need to make a complete online store with e-commerce, but I can’t choose which CMS to use) -
UserVote matching query does not exist
I'm having some trouble here and I can't figure out what's going on. I'm working on matching two users if they vote yes to each other, and then storing them in a database based on if they match, and then displaying them. If I manually add the users through admin, that works fine. In fact, if I were to remove the 2nd 'create_vote' method, the first one works just fine and stores the vote in a 'user_vote'object. However, when I add the second create_vote method, which I need to actually create 'matches', it doesn't work and it seems to be having a problem simply creating the vote to begin with. tracerback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 144, in nice return create_vote(request, profile_id, True) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 159, in create_vote vote=vote File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name dating_app.models.UserVote.DoesNotExist: UserVote matching query does not exist views.py/methods I use for matching def create_vote(request, profile_id, vote): profile = Profile.objects.get(pk=profile_id) UserVote.objects.create( … -
How to update data in specific form field in UpdateView Django
Since I'm new in Django how can I update specific form field in django? when I do {{ form.as_p }} in the template it works, but there are some form field('s) thats not needed to show on the other form but some it requires. so what I did is that call them only the required fill to be updated on some forms. here is my UpdateView: class SettingsProfileView(UpdateView): model = UserInfoModel template_name = 'site/views/settingsprofile.html' form_class = UserInfoForm success_url = '/' def get_object(self, queryset = None): if queryset is None: queryset = self.get_queryset() return get_object_or_404(queryset, users_id = self.kwargs['pk']) This class generic view actually working on the {{ form.as_p }} But there are some form fields that i dont want to be shown on that form. for those who wants to see my html templates: here it is -> {% extends 'roots/site.html' %} {% block content %} <div class="card col-lg-12"> <div class="card-body"> <div class="card-title"><h3>Personal Information Settings</h3></div> <form action="" method="post"> {% csrf_token %} <div class="form-group"> {{ form.firstname.label_tag }} {{ form.firstname }} </div> <div class="form-group"> {{ form.lastname.label_tag }} {{ form.lastname }} </div> <h4>Birthdate: </h4> <table> <tr> <td>{{ form.birthdate_month.label_tag }}</td> <td>{{ form.birthdate_day.label_tag }}</td> <td>{{ form.birthdate_year.label_tag }}</td> </tr> <tr> <td>{{ form.birthdate_month }}</td> <td>{{ form.birthdate_day }}</td> <td>{{ … -
How to use the shell_plus (iPython) console in PyCharm?
I'm learning to develop in Django and I'm using PyCharm on my project and I would like to use the iPython console in it. iPython launches, this is not the issue. The issue is that when I launch iPython from the console, all my models and other utils classes are imported. This is what happens when I launch the python3 manage.py shell_plus command: # Shell Plus Model Imports from app.models.models import Model1, Model2, Model3 from django.contrib.admin.models import LogEntry from django.contrib.auth.models import Group, Permission, User from django.contrib.contenttypes.models import ContentType from django.contrib.sessions.models import Session # Shell Plus Django Imports from django.core.cache import cache from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction from django.db.models import Avg, Case, Count, F, Max, Min, Prefetch, Q, Sum, When, Exists, OuterRef, Subquery from django.utils import timezone from django.urls import reverse /myproject/env/lib/python3.7/site-packages/IPython/core/history.py:226: UserWarning: IPython History requires SQLite, your history will not be saved warn("IPython History requires SQLite, your history will not be saved") Python 3.7.4 (default, Jul 23 2019, 18:02:54) Type 'copyright', 'credits' or 'license' for more information IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: Meanwhile when I start the Python Console in PyCharm, no import has been … -
Return the value of the tuple choices in Django
I want to return the string representation of the object, but it returns the code instead. How can i get the second item of the tuple? PACKAGE_TYPES = [ ('FR','Free'), ('BA','Basic'), ('PR','Professional'), ] class Package(models.Model): package_type = models.CharField(choices=PACKAGE_TYPES,max_length=2,default='FR') def __str__(self): return self.package_type -
celery - Task is not running despite being registered. Celery console does not reflect reception of task
After reviewing many many threads on the same issue, I have found no answer yet. I'm running a Django app with the following things Python: 3.6 Django: 3.0.5 Celery: 4.0.2 Kombu: 4.2.0 I'm running all the stack with docker-compose, celery is running in a different container. Apparently my task is registering within celery, because if I inspect the registered tasks of my application I get a list with a single element, the task itself: $ celery -A apps.meals.tasks inspect registered -> celery@7de3143ddcb2: OK * apps.meals.tasks.send_slack_notification myproj/settings.py INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps', 'apps.meals', ] myproj/celery.py: from __future__ import absolute_import, unicode_literals from celery import Celery import os from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproj.settings') app = Celery('myproj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.update( BROKER_URL=settings.BROKER_URL, ) My task is in a different place, within the meals app, in a file named tasks.py. myproj/apps/meals/tasks.py from django.conf import settings from slackclient import SlackClient from celery.utils.log import get_task_logger from myproj import celery_app from json import loads, dumps logger = get_task_logger(__name__) slack_markdown_text = "Hola!\n El menu de hoy es:\n {content}\n Pueden enviar su pedido aca: {link}\n Saludos!" @celery_app.task(name="apps.meals.tasks.send_slack_notification") def send_slack_notification(serial_menu, serial_options): ... My file structure is like: technical-tests/ | |--apps/ |----*snap |----meals/ |------*snap |------tasks.py |--myproj |----*snap … -
Django rest framework, use objects as choices in field
I have a model that one of the fields is a many to one relation. I want to give the user the ability to choose from existing objects of the model, I've tried many approaches about it including using SerializerMethodField and more. the closest I got was this: class MissionSerializer(HyperlinkedModelSerializer): queryset = KnownLocation.objects.all() known_location = ChoiceField(choices=queryset, read_only=True) gdt = KnownLocationSerializer(many=False, read_only=True) redirect_to_knownlocation = URLField # not implented yet. class Meta: model = Mission fields = ('MissionName', 'UavLatitude', 'UavLongitude', 'UavElevation', 'Area', 'gdt', 'known_location') Which showed the objects in the choices but didn't save new object since it's a read only field. the solution I've been thinking of is using Django's cache somehow to cache the KnownLocation objects somehow (which would save queries too) and import it into the Mission Serializer and use it as choices. Is something like this possible? class Mission(models.Model): """ Base mission model. gdt is a KnownLocation model Object. UAV Objects are Different, they have user specified elevation and area is not relevant to them (Contains area in the Mission object anyway). so association to KnownLocation object would be a db and request to google api waste. We don't want to connect them to each other or other … -
Django- mathematical operation between property of 2 separate instance in model
This is my first post here.. So if i miss something or did something wrong.. I am very sorry My Model class state(models.Model): name = models.CharField(max_length =50, null= True) def __str__(self): return self.name class county(models.Model): name = models.CharField(max_length =50, null= True) stateName = models.ForeignKey(state, null= True, on_delete = models.SET_NULL) def __str__(self): return self.name class cityPopulation(models.Model): forCounty = models.ForeignKey(county, null= True, on_delete = models.SET_NULL) city1Popultaion = models.IntegerField(null =True, blank =True) city2Population = models.IntegerField(null =True, blank =True) def __str__(self): return self.forCounty.name + str("'s population data") @property def totalPoulation(self): total = int(self.city1Popultaion + self.city2Population) return total Here is my question with totalPouplation i can get total of each instance of cityPopulation. Lets say we have 2 states with 2 counties with city1 and city2 each is there is a easy way i can get total population of each state Any help would be great thanks a lot I am just learning Django.. so i am very much beginner -
How can i fix the Django Admin panel logging error?
when im login to /admin page, server does down. But other pages doesn't like that. Note: already created superuser. 1st time i logged to control panel then i tried to login it. but cant then delete the super user and create it again result was like above. i changed the server port, web browser. but result is same Need solution for this -
Problems with creating session
I have project with rooms where we have private rooms with passwords, i want to create session that will allow you to join group without password after first successfull joining. I did that but it giving access to every room after first successfull joining not only to group that i joined. How to fix that? views.py def auth_join(request, room, uuid): room = get_object_or_404(Room, invite_url=uuid) if request.session.get('joined', False): return HttpResponseRedirect(Room.get_absolute_url(room)) else: try: room_type = getattr(Room.objects.get(invite_url=uuid), 'room_type') except ValueError: raise Http404 if room_type == 'private': if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): try: room_pass = getattr(Room.objects.get(invite_url=uuid), 'room_pass') except ValueError: raise Http404 password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return HttpResponseRedirect(request.get_full_path()) else: user = CustomUser.objects.get(username=user) try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 assign_perm('pass_perm',user, room) if user.has_perm('pass_perm', room): request.session['joined'] = True join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) else: return HttpResponse('Problem issues') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) else: try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 return HttpResponseRedirect(Room.get_absolute_url(room)) -
django.db.utils.OperationalError: FATAL: password authentication failed for user "vagrant"
I had a problem with my vagrant boxes with ports and everything so I did something that I suspect is inhibiting my ability to run ./manage.py migrate. Here's what it looks like when I run vagrant ssh-config HostName 127.0.0.1 User vagrant Port 2222 UserKnownHostsFile /dev/null StrictHostKeyChecking no PasswordAuthentication no IdentityFile /Users/brock1hj/projects/sodium/to-vagrant/.vagrant/machines/default/virtualbox/private_key IdentitiesOnly yes LogLevel FATAL Here is the full error: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/migrations/loader.py", line 180, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/backends/base/base.py", line 135, in _cursor self.ensure_connection() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/Users/brock1hj/envs/sodium/lib/python2.7/site-packages/django/db/backends/base/base.py", line 119, in …