Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i want to make a website live which is build on python django
I have developed a website using python on Django framework now I want to host this website. I am complete fresher. please give me steps to host my website. I want to make it live. -
Retriving random records from database depending on an attribute value until a limit, and complete with other if the limit is not reached
I'm using Django with Postgres. On a page I can show a list of featured items, let's say 10. If in the database I have more featured items than 10, I want to get them random/(better rotate). If the number of featured item is lower than 10, get all featured item and add to the list until 10 non-featured items. Because the random takes more time on database, I do the sampling in python: count = Item.objects.filter(is_featured=True).count() if count >= 10: item = random.sample(list(Item.objects.filter(is_featured=True))[:10]) else: item = list(Item.objects.all()[:10]) The code above miss the case where there less than 10 featured(for example 8, to add 2 non-featured). I can try to add a new query, but I don't know if this is an efficient retrive, using 4-5 queries for this. -
django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server
I am trying django on appengine standard environment, using cloud sql for database, I have already seen : https://groups.google.com/forum/#!topic/google-appengine/pl_zwg8Tmjc in settings.py I have if os.getenv('GAE_APPLICATION', None): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/<your-cloudsql-connection string> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/MYPRO-9879789777:us-central1:myproject', 'USER': '[USERNAME]', 'PASSWORD': [PASSWORD]', 'NAME': '[DATABASENAME]', } } else: # Running locally so connect to either a local MySQL instance or connect to # Cloud SQL via the proxy. To start the proxy via command line: # # $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306 # # See https://cloud.google.com/sql/docs/mysql-connect-proxy DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/MYPRO-9879789777:us-central1:myproject', 'PORT': '3306', 'USER': '[USERNAME]', 'PASSWORD': [PASSWORD]', 'NAME': '[DATABASENAME]', } } I have this code running in another tab ./cloud_sql_proxy -instances="MYPRO-9879789777:us-central1:myproject"=tcp:3306 And in another tab I am running python manage.py makemigrations and it is giving mw the following error: Traceback (most recent call last): File "/home/sugumar/myproject/env/lib/python3.5/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/sugumar/myproject/env/lib/python3.5/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/sugumar/myproject/env/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection return Database.connect(**conn_params) File "/home/sugumar/myproject/env/lib/python3.5/site-packages/MySQLdb/init.py", line 85, in Connect return Connection(*args, **kwargs) File "/home/sugumar/myproject/env/lib/python3.5/site-packages/MySQLdb/connections.py", line 204, in init super(Connection, self).init(*args, **kwargs2) _mysql_exceptions.OperationalError: (2002, "Can't connect to local … -
ck editor media uploader has problem when using nginx
I am using Ckeditor as a rich text editor in one of my django app. when I test it on my localhost it worked properly and when I tried to push them to server the ckeditor worked properly again. ( it could upload media and also load the browse server page that include my previous uploaded media files. but when I start nginx to keep my code running on server,ck editor can't upload any media and it shows the error below: 405 error returned from ck editor and when I click one browse server button on the main page of ckeditor uploader it redirect me to the homepage of my site but it shouldn't do this and should show the ckeditor database page: ckuploader main page I guess its because of my locations that I set in nginx/sites-available but I don't Know how can I fix them. I should mention that didn't any setup as ckeditor locations and i just have to location: 1: location / { root /var/www/html/front_end/dist; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. #try_files $uri $uri/ =404; try_files $uri $uri/ index.html $uri$args $uri$args/ /index.htm$ } … -
integrity error for a variable that does not exist
(django.db.utils.IntegrityError: UNIQUE constraint failed: items_purchase.item_id) this is the error that I get when I try to migrate the app named 'items'. app name = items model name = Purchase i don't understand what is item_id. -
django rest framework: how to add custom css class to the ModelSerializer
I'm using django rest framework and I want to add extra css class names to the PostSerializer's fields. This is my code: models.py class Post(models.Model): title = models.CharField(default="New Post", max_length=50) text = models.TextField(blank=True, null=True) serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'title', 'text') A field like title will be rendered as: <div class="form-group "> <label >Title</label> <input name="title" class="form-control" type="text" value="" > </div> There is already a class form-control exist, I want to add another one, how could I achieve it? -
Django sanitize Raw Queryset that receives user input
I need to do a RAW query in Django, and I need to sanitize the input. I create the query starting from a base string: qs_str = 'SELECT c.name, l.adds FROM company inner join lace ...WHERE..' Then based on multiple conditions I modified: if x: qs_str = ' '.join([qs_str, 'AND alpha=true ']) if self.request.GET.get('q'): qs_str = ' '.join([qs_str, 'AND name=self.request.GET.get('q')]) if self.request.GET.get('ct'): ... Then I create the Queryset: qs = Company.objects.raw(qs_str) The query is modified based on some internal variables, and dependent on user input. Off course the user input I need to sanitize. I know that in Raw Queryset you can declare variables, name = %s'AND ads = %s, [lname, adds]) but because are added at the end, I have to do the check twice: First time when I create the query Second time, to check to know what variables to add after the query That means I do the same checks twice, and I have at least 5 checks, so if is possible to avoid reapeting the checks(ifs) -
Extract UserID from FireBase
How to extract User from the Firebase account in Django to access the user id from the firebase only? config = { 'apiKey' : "", 'authDomain' : "", 'databaseURL': "", 'projectId': "", 'storageBucket': "", 'messagingSenderId': "" } # firebase.initializeApp(config); firebase = pyrebase.initialize_app(config) auth = firebase.auth() db = firebase.database() -
Django-Restframework with Mysql in docker
I have dockerized my existing Django Rest project which uses MySQL database. Dockefile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt requirements.txt django djongo django-rest-framework wheel pillow mysqlclient django-cors-headers docker-compose.yml version: '3' volumes: portainer: services: db: image: mysql environment: MYSQL_ROOT_PASSWORD: docker MYSQL_DATABASE: docker MYSQL_USER: docker MYSQL_PASSWORD: docker ports: - "3306:3306" web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000 " volumes: - .:/code ports: - "8000:8000" links: - db portainer: image: portainer/portainer ports: - "9000:9000" volumes: - /var/run/docker.sock:/var/run/docker.sock - portainer:/data setting.py 'ENGINE': 'django.db.backends.mysql', #django.db.backends.mysql 'NAME': 'docker', #local: libraries #server: 'USER': 'docker', #root #root 'PASSWORD': 'docker', #local: root #server: 'HOST': 'db', #local: localhost #server: 'PORT': '3306', My command 'docker-compose up -d --build' are successful but the restapp container was not started so while checking logs it was showing this error django.db.utils.OperationalError: (2003, 'Can\'t connect to MySQL server on \'db\' (111 "Connection refused")'). -
Django RelatedObjectDoesNotExist when cleaning form and accessing self.instance.user
I cannot quite figure out why when trying to access self.instance.user when overriding the clean method of my form, I am getting some RelatedObjectDoesNotExist. This does not happen every time and almost seems to be random which is why it's causing me a lot of trouble. See below for my form and model forms.py class UserSurveyQueueForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user') super().__init__(*args, **kwargs) self.fields['queue'].queryset = Employees.objects.all() self.fields['queue'].required = False def clean(self): cleaned_data = self.cleaned_data users_added = cleaned_data.get('queue') if users_added: for user in users_added: if user == self.instance.user: raise forms.ValidationError("Yikes, you can't add {} to {}'s queue!".format( self.instance.user.employee.first_name, self.instance.user.employee.first_name )) last_created = UserNPS.objects.filter(user=user.employee, reporter=self.instance.user.employee).values( 'created_at').last() if last_created: timedelta = (timezone.now() - last_created['created_at']).days if timedelta <= settings.DAYS_BETWEEN_SURVEYS: raise forms.ValidationError("You have recently filled out a survey for {} {}, please wait {} days before doing so again!".format( user.employee.first_name, user.employee.last_name, settings.DAYS_BETWEEN_SURVEYS - timedelta)) class Meta: model = UserSurveyQueue fields = ('queue',) widgets = { 'queue': autocomplete.ModelSelect2Multiple( url='user-autocomplete', attrs={ 'data-placeholder': 'Search by name, username, email, department, office, or team', } ), } models.py class UserSurveyQueue(models.Model): user = models.OneToOneField( Employees, on_delete=models.CASCADE ) queue = models.ManyToManyField( Employees, blank=True, related_name='survey_queue', ) class Meta: verbose_name = ('Survey Queue') verbose_name_plural = ('Survey Queues') def current_queue(self): return ", ".join([str(q.employee.username) … -
How can I change the default font using in django admin interface?
I wanna know how can I change the default font using in django admin interface? Brgds -
how do I fix CharField attribute error in django?
I am a beginner and this might seem very trivial to most. I am getting an the following error: Traceback (most recent call last): File "C:\Dev\hoss\myfirst\app_one\models.py", line 3, in class Question(models.Model): File "C:\Dev\hoss\myfirst\app_one\models.py", line 5, in Question textone = models.CharField(max_lenght=128) File "C:\Dev\hoss\lib\site-packages\django\db\models\fields__init__.py", line 1037, in init super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'max_lenght' for the following code and cant fix it any body can help: from django.db import models class Question(models.Model): textone = models.CharField(max_lenght=128) pub_date = models.DateTimeField() class Choice(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) text = models.CharField(max_lenght=200) vote = models.IntegerField(default = 0) -
I receive an error stating that a particular migrations file does not have a Migration file, but it does
Error: django.db.migrations.exceptions.BadMigrationError: Migration 0011_add_relevant_permissions_to_admin_and_operators in app config has no Migration class This error body suggests to me that I haven't put the Migration class in the mentioned file but as I've posted below, the code of my file does have the Migration class and it inherits from the migrations.Migration code of the 0011_add_relevant_permissions_to_admin_and_operators migrations file: from django.db import migrations from django.contrib.auth.models import Permission class Migration(migrations.Migration): dependencies=[ ('openwisp_user', '0004_default_groups'), ('config', '0010_auto_20180106_1814'), ] operations=[ migrations.RunPython(assignPerm), ] def assignPerm(apps, schema_editor): Group= apps.get_model('openwisp_user', 'Group') admin = Group.objects.get(name="Administrator") operator= Group.objects.get(name="Operator") operators_and_admins_can_change=["device", "config", "template", "location", "floorplan",] operators_read_only_admins_manage=["vpn", "ca", "certificate",] manage_operations=["add", "change", "delete"] for i in operators_and_admins_can_change: for j in manage_operations: admin.permissions.add(Permission.objects.get(codename="{}_{}".format(j,i)), bulk=True) operator.permissions.add(Permission.objects.get(codename="{}_{}".format(j,i)), bulk=True) for i in operators_read_only_admins_manage: try: permission=Permission.objects.get(codename="view_{}".format(i)) operator.permissions.add(permission, bulk=True) except Permission.DoesNotExist: pass for j in manage_operations: admin.permissions.add(Permissions.objects.get(codename="{}_{}".format(j,i)), bulk=True) -
Retrieving data from a database in Django and using that data in templates
I'm trying to retrieve data from my Django application database but I can't seem to do it right. I have a model which I am using to render a form. I am simply trying to retrieve the price of an issue so it can be displayed on the rendered template when a user is redirected after form submission. But all I still get is Add Price in the rendered template. Here's my code: models.py class Issue(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='issue') number = models.PositiveIntegerField(null=False, blank=False) title = models.CharField(max_length=500, null=False, blank=False) body = models.TextField(null=False, blank=False) price = models.DecimalField(max_digits=6, decimal_places=2, null=False, blank=False) url = models.URLField(null=False, blank=False) details = models.TextField(null=False, blank=False) date = models.DateTimeField(auto_now_add=True) forms.py class IssueProcessForm(forms.ModelForm): ... class Meta: model = Issue fields = ( 'user', 'price', 'details', 'number', 'title', 'body', 'url' ) views.py ... if request_issue.status_code == requests.codes.ok: issue = request_issue.json() if request.method == 'POST': form = IssueProcessForm(request.POST, initial={ 'number': issue['number'], 'title': issue['title'], 'body': issue['body'], 'url': issue['html_url'] }) if form.is_valid(): issue = form.save(commit=False) issue.user = request.user issue.save() messages.success(request, 'Issue Processed Successfully!') return redirect('core:repository_issues', repository_name=repository_name) else: messages.error('request', 'Oops, Something happened. Try again!') else: form = IssueProcessForm(initial={ 'number': issue['number'], 'title': issue['title'], 'body': issue['body'], 'url': issue['html_url'] }) get_price = Issue.objects.get(number=issue['number'], title=issue['title']) return render(request, 'core/process_issue.html', … -
get index of for loop when using formset django
template: {% for image in obj.images_set.all %} <div id="myModal{{forloop.counter0}}" class="modal fade" role="dialog"> <div class="modal-dialog" style="text align:center;"> <div class="modal-content" style="display:inline-block;"> <img src="{{ image.image.url }}" alt=""/> </div> </div> </div> {% endfor %} Im using a for loop on images which has a image set ..Im using modals here so the id should be modal1,modal2 modal3 etc and get incremented on each looping ..But as of now ,it is not incrementing ...How to do this?The imageset for each loop has a maximum of 3 and min of one image! -
django celery import function not working
I have been trying to create a task for a while, which consists of creating a sample of a specimen every 5 hours. I have managed to configure celery with redis and execute the task that is as an example in the documentation but when I want to do something more complex that includes a query set it does not execute me.the task disappears from the list when restarting the queue. what I'm trying to do is this: from .models import Muestra from backend.Servicios.models import Servicio def generar_muestras(): services = Servicio.models.all() for i in services: muestra = Muestra(servicio_id=i.id) muestra.save -
Cannot access django-rosetta since I added a new app to project
I have been using django-rosetta for a while in my project, but when I added a new app ExcursionsManagerApp, I get this error when I try to access rosetta's admin page: AttributeError at /es/rosetta/files/project/ module 'ExcursionsManagerApp' has no attribute '__file__' I don't know what causes the error. -
How to create an BytesIO img and pass to template
Based on data, I am attempting to pass a BytesIO img_in_memory from DetailView to the template. I suspect that I am making a simple and fundamental error in relation to passing the context data to the template, although, I can't figure out what it is. CODE Views.py def get(self, request, *args, **kwargs): self.get_histogram(request) return super(SearchResultsView, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(SearchResultsView, self).get_context_data(**kwargs) return context def get_histogram(self, request): """ Function to create and save histogram of Hashtag.locations """ # create the histogram plt.show() img_in_memory = BytesIO() plt.savefig(img_in_memory, format="png") image = base64.b64encode(img_in_memory.getvalue()) context = {'image':image} return context Results.html <img src="data:image/png;base64,{{image}}" alt="Location Histogram" /> -
Django website doesn't load some sections of website from some countries
Would anybody please help me with this strange situation? My website jehlum.org is working perfectly when browsed from Asia or Europe but when you try to browse it from US, the ads section (one of the 3 sections on homepage) disappears. I even tried changing vps provider but to no avail. Any idea why is this happening? Had it been geographical kind of restriction on my domain then while website shouldn't load in browser, but this is something partial. Regards/ -
Can't change a model field type in Django
I have a model ReservationSupplement: class ReservationSupplement(models.Model): reservation_hotel = models.ForeignKey(ReservationHotel, on_delete=models.CASCADE, related_name='supplements', verbose_name=_("Hotel Supplements")) supplement = models.CharField(max_length=10) And I want to change it to: class ReservationSupplement(models.Model): reservation_hotel = models.ForeignKey(ReservationHotel, on_delete=models.CASCADE, related_name='supplements', verbose_name=_("Hotel Supplements")) supplement = models.ForeignKey('RatesManagerApp.Product', on_delete=models.PROTECT, related_name='reservations', verbose_name=_("Supplement")) I had no problem with the makemigrations, but when I run migrate, I get this error: django.db.utils.ProgrammingError: column "supplement" does not exist. I don't know what causes it because the traceback only gives me Django modules and no clue of what causes the error to arise. -
Django: render radiobutton with 3 columns and make last 2 conditional on other field
I need to replicate this form: https://www.stickermule.com/products/die-cut-stickers A) In the Select a Quantity part there are radiobutton that show the 1) quantity, 2) price, 3) savings. I need to know how to construct my model so I can show those 3 values in a single row. B) The 2) price and 3) savings columns must change according to the **Select a Size" selection. My current model: class TamaniosCantidades(models.Model): TAMANIOS = (('2x2', '2" x 2"',), ('3x3', '3" x 3"',), ('4x4', '4" x 4"',), ('5x5', '5" x 5"',)) CANTIDADES = (('50', '50',), ('100', '100',), ('150', '150',)) # usuario = models.ForeignKey(User, on_delete=models.DO_NOTHING) tamanios = models.CharField(max_length=10, choices=TAMANIOS) cantidades = models.CharField(max_length=10, choices=CANTIDADES) forms.py class TamaniosCantidadesForm(forms.ModelForm): tamanios = forms.ChoiceField(choices=TAMANIOS, widget=forms.RadioSelect(), label='Selecciona un tamaño') cantidades = forms.ChoiceField(choices=CANTIDADES, widget=forms.RadioSelect(), label='Selecciona la cantidad') class Meta: model = TamaniosCantidades # fields = ['tamanios', 'cantidades',] -
How to install django-tinymce properly? Easy instructions?
I'm working on a project for a course, and we have to learn a lot of this stuff off the cuff.... Anyhow, I'm having one hell of a time getting this to work properly. Can someone please walk me through a basic installation of django-TinyMCE, including any paths I should be aware of needing to configure? Please help. We're running tight on time and I have virtually no clue what I'm doing when it comes to django. I'm running (obligatory) django 2.1.0. Particularly confusing to me is JS_ROOT and JS_URL. What am I supposed to set these to for a typical project configuration? Please help me. I'm desperate and I've already been at this for several hours without any luck. -
django-fluent-contents not installing correctly in django.settings.installedApps
Hello fellow programmers, I´m following the steps to install django-fluent-contents from the link https://django-fluent-contents.readthedocs.io/en/latest/ quickstart.html 1- pip install django-fluent-contents 2- Basic setup Next, create a project which uses the module. The basic module can be installed and optional plugins can be added: INSTALLED_APPS += ( 'fluent_contents', 'django_wysiwyg', # And optionally add the desired plugins: 'fluent_contents.plugins.text', # requires django-wysiwyg 'fluent_contents.plugins.code', # requires pygments 'fluent_contents.plugins.gist', 'fluent_contents.plugins.googledocsviewer', 'fluent_contents.plugins.iframe', 'fluent_contents.plugins.markup', 'fluent_contents.plugins.rawhtml', ) 3- pip install django-fluent-contents[text,code] 4- then running python manage.py migrate and then, error message: D:\projetos\fluent\fluentdemo>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\ProgramData\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\ProgramData\Anaconda3\lib\site-packages\fluent_contents\plugins\text\models.py", line 6, in <module> from fluent_contents.extensions import PluginHtmlField File "C:\ProgramData\Anaconda3\lib\site-packages\fluent_contents\extensions\__init__.py", line 12, … -
Nginx site cannot be accessed through domain URL
The problem: I have set up a (Docker) Django-Gunicorn-Nginx site on my home network. It works on the local network but I cannot access it through my domain. The setup: Registered a domain in namecheap.com. Set up a dynamic DNS to update my public IP with the namecheap domain. Set up the website on a computer in my home network and give it a static IP. Enable port forwarding from public 80 to LAN 80. The tests: I have enabled port forwarding on the port 22 and I have been able to connect through SSH to the computer serving the website with ssh user@domain and it worked well -> domain/ddns ok. I have accessed to the website from another computer connected on the same LAN by using the full static IP to the computer serving the website and it worked well -> website/server ok. I have called my ISP to check if everything is set up correctly and if I am allowed to serve a website form my network and apparently there are no issues -> router/network ok. The clue: When I try to access the site from outside my home network, through the domain or my full public IP, … -
Django: sensitive_post_parameters didn't receive an HttpRequest
I am trying to set a flag when a user's password is changed through the admin application. Therefore, in 'admin.py' I have the following code: class CustomUserAdmin(UserAdmin): @sensitive_post_parameters_m def user_change_password(self, request, id, form_url=''): #if password was changed through admin, set force_password_change = True return super().user_change_password(self, request, id, form_url='') As you can see, I am using the decorator @sensitive_post_parameters_m which also the super method of user_change_password has. However, I am getting an assertion error: AssertionError at /admin/auth/user/9/password/ sensitive_post_parameters didn't receive an HttpRequest. If you are decorating a classmethod, be sure to use @method_decorator.