Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to receive and save data via ajax in django?
through ajax I am sending the data correctly, because the data I see through wireshak and they are correct. On the django server, he sends me the correct request "POST / solit / HTTP / 1.1" 200 52. But the value sent does not receive it, it does not reach the Mysql database and I do not understand why, if the traffic sends well the data. In wireshak I see the data of the post request, they are the correct ones, but they are not saved in the database, when I want them to be added as if I were to update the record of such database fields and it does not , I do not understand why this is my views.py def solit(request): if request.method == 'POST' and request.is_ajax(): form = addiForm(request.POST) if form.is_valid(): peticion = form.save() if peticion.usuario: peticion.usuario.d_pendientes = form.cleaned_data.POST.get['dias_adicionar', None] # Get the form value if has, otherwise assign it to None (change it if you want another default value) peticion.usuario.h_pendientes = form.cleaned_data.POST.get['horas_adicionar', None] # The same peticion.usuario.save() print (request.get) return JsonResponse({'status': 'true', 'msg': 'Procesado Correctamente'}) else: return JsonResponse({'status': 'false', 'msg': 'Los datos no son validos'}) form = addiForm() return render(request, 'plantillas/adicionar.html', {'form':form}) This is my … -
Django app changes in server after a while
I'm running a Django app on an AWS EC2 instance. When I upload the app it works fine for a while and all of a sudden some problems appear. First, it doesn't find the media folders that initially found and second, if I fix the paths to the media folders, it returns a problem with urlpatterns, which doesn't make sense since the app works for an hour or so until it doesn't. To fix the issue I have to reupload the app but after a couple of hours it happens again. Any solutions? -
How to Embed a Plotly Interactive Graph in Webpage
I have an interactive graph generated by Plotly in Python that I saved to an html file using plotly.offline.plot(fig, filename='/tmp/interactiveGraph.html') I am now trying to embed this interactive graph into some kind of webpage, using either Dash or Django. I'm leaning toward Django at the moment, given that I have an html version of the graph. Which would be better? My code for the webpage is in a separate file from the code where I am creating the graph. A lot of the tutorials I've found online just say to add a few lines to the template, but I don't know how to get those lines that they've described. tl;dr: I'm looking for guidance as how to integrate an html file-for a Plotly interactive graph-with a web python script using Django or Dash Reference: https://github.com/ricleal/DjangoPlotLy https://www.pythonsetup.com/how-implement-data-visualization-django-and-plotly/ -
Django filter objects based on property in ForeignKey set
I have models that look something like this: class Type(models.Model): name = models.CharField(max_length=50) notes = models.CharField(max_length=50) class Instance(models.Model): type = models.ForeignKey(Type, on_delete=models.CASCADE) color = models.CharField(max_length=50) quantity = models.PositiveIntegerField() I want to get a list of all Types that have at least one Instance whose quantity is greater than 0. How can I express that? In (pseudo) vanilla Python, this would be something like: [type for type in Type.objects.all() if type.instance_set.objects.filter(lambda instance: instance.quantity > 0)] I tried available_types = Type.objects.filter(Q(instance_set__contains=Q(quantity__gt=0)) but this doesn't work because Django is looking for quantity as an attribute of Type, and of course doesn't find it, because it's an attribute of Instance. -
How to make serializer which could return list in ApiView?
I tried to make API which will return me list of "listing" id for authenticated user, but I did it without any serializer. my view : class AuthUserFavoriteListingsView(APIView): """List of favorite user listings""" permission_classes = (IsAuthenticated, ) def get(self, request): listings = UserListingFavorite.objects.filter(user=request.user).values_list('listing_id', flat=True) return Response({"listings": listings}) it is my result: { "listings": [ 9, 11 ] } Is there any way to get the same result with the serializer? -
TypeError at /modelo/matricula save() missing 1 required positional argument: 'self'
Hola como estas soy nuevo en django bueno mi asunto es que quiero guardar en mi tabla matriculas las llaves de los estudiantes el grupo y el anyo pero me dice save() missing 1 required positional argument: 'self' entoces no se def matricula(request): if request.method=='POST': form=matriculaForm(request.POST) if form.is_valid(): matricula=matriculaForm.save() matricula.save() return redirect('correcto') else: form=matriculaForm() return render(request,'matricula.html',{'form':matriculaForm}) esa es la vista este el modelo class matricula(models.Model): codigo=models.ForeignKey(alumno,default=None,null=False,on_delete=models.CASCADE) grado=models.ForeignKey(grado,default=None,null=False,on_delete=models.CASCADE) anyo=models.ForeignKey(anyo,default=None,null=False,on_delete=models.CASCADE) -
How to get the date from the date picker in django
I am trying to get the date from the user using date picker in django. But I am just getting none despite user picking up a date . I followed this tutorial https://simpleisbetterthancomplex.com/tutorial/2019/01/03/how-to-use-date-picker-with-django.html I am trying to get the date using the cleaned.data. date = form.cleaned_data['date'] How do I get the date user selects. Also, I want the hour and minute field in date picker This is my date field in the form (I am using forms.form) class DateForm(forms.Form): date = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=forms.DateTimeInput(attrs={ 'class': 'form-control datetimepicker-input', 'data-target': '#datetimepicker1' }) ) Here is the code in my HTML file <div class="input-group date" id="datetimepicker1" data-target-input="nearest"> <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1"/> <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <script> $(function () { $("#datetimepicker1").datetimepicker(); }); </script> -
Change Django setting ALLOWED_HOSTS in settings.py only when running pytest
I've got a test that I'm trying to run where I login to my django application: class FirefoxTestCases(StaticLiveServerTestCase): def setUp(self): data_setup.basic_apps_setup(self) self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_log_in_with_no_apps_displays_firefox(self): # Opening the link we want to test self.browser.get(self.live_server_url) assert "log in" in self.browser.page_source time.sleep(2) self.browser.find_element_by_id("id_username").send_keys("userone") self.browser.find_element_by_id("id_password").send_keys("test") self.browser.find_element_by_id("log_in").click() time.sleep(2) # Check the returned result assert "Something appears to be missing" in self.browser.page_source In doing this - it doesn't actually allow the login because in my settings I have specific ALLOWED_HOSTS setup. Is there a way to access the ALLOWED_HOSTS settings when running this test so that it will allow login when testing? -
Reading Dictionary in Array with Django to HTML
I have the following dictionary: export = { 'target': target_name, 'chats': [ { 'name': 'name', 'time': 'time', }, { 'name': 'name', 'time': 'time', }, ], } What I want to do is to pass these values to a dynamically generated HTML file. {{ for chat in chats }} <h3>{{ chat.name }}</h3> {{ endfor }} If I try to do this it returns the following error: Could not parse the remainder: ' chat in chats' from 'for chat in chats' I am already returning the dictionary, so I can do <h3>{{ target }}</h3> -
Django runserver hangs at “System check identified no issues (0 silenced).” for a while
I am not able to start manage.py runserver 0.0.0.0:8000. I am using a MySQL database and I have imported all the required modules. I am trying to run quite basic application. I am running python 3.7.3 on windows 10. Here is the error I am getting: System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000005A89E18> Traceback (most recent call last): File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\utils\aut oreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\core\mana gement\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\core\mana gement\base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\migrat ions\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\migrat ions\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\migrat ions\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\migrat ions\recorder.py", line 62, in applied_migrations return {tuple(x) for x in self.migration_qs.values_list('app', 'name')} File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\models \query.py", line 268, in __iter__ self._fetch_all() File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\models \query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) MemoryError -
How Do I Stop Recursive GET For Python/Django/Javascript?
I've spent the last couple days trying to figure out the answer to this SO...ModelChoiceField invalid literal for int() with base 10: '' Leveraging this solution, How to prevent submitting the HTML form's input field value if it empty I'm really close. The problem is...I'm using a django DetailView and overriding GET to try and get the value that is being passed by Javascript, but it's essentially looping when I perform my GET. I'm new to Javascript, and it's entirely possible that my Javascript program is incorrect. Here is my code.... My Django DetailView... class AuthorDetailView(LoginRequiredMixin,DetailView): model = Author template_name = 'author_detail.html' def get_object(self, queryset=None): return get_object_or_404(Author, id=self.request.GET.get("dropdown")) def get(self, request, *args, **kwargs): dropdown=self.request.GET.get("dropdown") if dropdown: print(dropdown) try: if Author.objects.filter(Q(id=self.request.GET.get("dropdown"))).distinct(): self.object = self.get_object() return HttpResponseRedirect(reverse('Main:author_detail')) else: messages.add_message(self.request, messages.INFO, 'Please enter a valid choice.') print(dropdown) return HttpResponseRedirect(reverse('Main:author_detail')) My HTML.... My FORM.... class AssociateByNameForm(forms.Form): dropdown = forms.ModelChoiceField(queryset=User.objects.none(),required=False) def __init__(self, *args, **kwargs): dropdown = kwargs.pop('dropdown', None) super(AssociateByNameForm, self).__init__(*args, **kwargs) self.fields['dropdown'].widget.attrs['class'] = 'choices' self.fields['dropdown'].empty_label = '' self.fields['dropdown'].queryset = Author.objects.filter(is_active=True).order_by('last_name','first_name') self.fields['dropdown'].label_from_instance = lambda obj: "%s" % obj.get_full_name() My Javascript.... $(document).ready(function () { $('form').submit(function() { var dropdown = $('#id_dropdown').val(); if (dropdown === undefined || dropdown === "") { $('#id_dropdown').attr('name', '' ); } }); }); From what … -
How do I Force db commit of a single save in django-orm in a celery task
I am using django and celery. I have a long running celery task and I would like it to report progress. I am doing this: @shared_task def do_the_job(tracker_id, *args, **kwargs): while condition: #Do a long operation tracker = ProgressTracker.objects.get(pk=tracker_id) tracker.task_progress = F('task_progress') + 1 tracker.last_update = timezone.now() tracker.save(update_fields=['task_progress', 'last_update']) The problem is that the view that is supposed to show the progress to the user cannot see the updates until the task finishes. Is there a way to get the django orm to ignore transactions for just this one table? Or just this one write? -
How to create profil model with foreign key
I want to create a dashboard for users for showing their SEO score. I have on my projet 3 apps: -Account : with a login/registration form using the Usercreation form basic of django. it has fields(email,firstname,last_name) -Analysis : With a scrapper that's scanning all the website and saving on the database the seo score, the email, and the consent to contact or not What I want to do is to merge these 2 tables, maybe using foreinkeys or I don't know what. For what? I want to have a table while when i click on the user on django admin, there is his name,last name, email, seo score, and his website, and he can login with his mail. On this dashboard I will show him all the data related to his website so that's why i have to make a connection between the login platform and the website scrapper. part of Settings.py : import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'key' # SECURITY WARNING: don't run with debug … -
How to create postgresql object from a Django script?
I have this code: import random import string def random_username_and_password(stringLength): letters = string.ascii_letters return ''.join(random.choice(letters) for i in range(stringLength)) username = random_username_and_password(random.randint(8, 12)) password = username To create a user, it is enough to register the following line User.objects.create_user(username, password) But I want to do this through connecting to the postgres database from a script. import sys,os if __name__ == '__main__': # pragma nocover # Setup environ sys.path.append(os.getcwd()) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "starnavi.settings") import django django.setup() from django.db import connections db_conn = connections['default'] try: c = db_conn.cursor() except OperationalError: connected = False else: connected = True But what to do next, I do not understand. I'm use Django 2.2, Python 3.7, Postgresql 9.5 -
How to pass context from views to JS file Django
I am using Google charts to show data in my webapp. Right now these charts are in the script tag in my templates (HTML) like so. <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'Low', {role: 'annotation'}, 'Medium', {role: 'annotation'}, 'High', {role: 'annotation'}, 'Emergency',], ['{{three_sun}}', 124, 124, 163, 163, 87, 87, 0], ['{{two_sun}}', 120, 120, 160, 160, 80, 80, 0], ['{{last_sun}}', 127, 127, 159, 159, 89, 89, 0], ['{{this_sun}}', {{total_low}}, {{total_low}}, {{total_medium}}, {{total_medium}}, {{total_high}}, {{total_high}}, {{total_emergency}}] ]); var options = { title: 'All Bugs', vAxis: {title: 'Total Bugs'}, isStacked: true }; var chart = new google.visualization.SteppedAreaChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> I am trying to clean up this project and have all my scripts coming from static .js files. Now obviously it doesn't recognize {{three_sun}}. I need to know how i can be able to use this chart with the context variables, from a static.js like so. chart.js google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'Low', {role: 'annotation'}, 'Medium', {role: 'annotation'}, 'High', {role: 'annotation'}, 'Emergency',], ['{{three_sun}}', 124, 124, 163, 163, 87, 87, 0], ['{{two_sun}}', 120, 120, 160, 160, 80, 80, 0], ['{{last_sun}}', 127, 127, 159, 159, 89, 89, 0], … -
Problem with django-multiselectfield and forms
I want to do a multiple selection in the models django and how it would turn out (I used the library), and now I try to make sure that only selected items from my model field are shown in my form, but I am faced with a small problem : AttributeError: 'MSFList' object has no attribute 'get_choices_selected' 1) I know that in this library there is a function get_choices_selected that returns selected items 2) I tried to use just the output of the model, but it returns the string data type: (( my models.py CHOSE_SIZE = (('XS', 'XS'), ('S', 'S'), ('M', 'M'), ('L', 'L'), ('XL', 'XL'), ('XXL', 'XXL'), ('XXXL', 'XXXL')) ....... available_size = MultiSelectField(choices=CHOSE_SIZE, verbose_name='Available Sizes', default=None) my forms.py class item_add_form(forms.Form): quantity = forms.IntegerField(max_value=21, min_value=0) size = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOSE_SIZE) def __init__(self, *args, **kwargs): choices = kwargs.pop('choices', None) super(item_add_form, self).__init__(*args, **kwargs) self.fields['size'] = forms.ChoiceField(widget=forms.RadioSelect, choices=choices) my views.py class MainPage(views.View): products = Product.objects.get(ordered__gt=0) form = item_add_form(choices =products.available_size.get_choices_selected()) contex = {'products' : products, 'form_input': form } def get(self, request): return render(request, 'MainPage/Mainpage.html', context=self.contex) I will be glad to any help, and I ask your advice: 1) Is it possible to fix this somehow? 2) Or how to do it better? -
How to call a view with many parameters
I am trying to create a very simple custom view for my application. Lets imagine I have a simply model: class Person(models.Model): Name = models.CharField(max_length = 255) pass class Company(models.Model): Title = models.CharField(max_length = 255) pass I would like to display a list of objects. On one url - list of person, on another - list of companies. So I create simply views: def PersonListView (request): _persons = Person.objects.all() context = { "object_list": _persons } return render (request, "PersonListView.html", context) def CompanyListView (request): _companies = Person.objects.all() context = { "object_list": _companies } return render (request, "CompanyListView.html", context) Then add path to urls - /Person for list of persons and /Company for list of companies. urlpatterns = [ path('/Person', PersonListView), path('/Company', CompanyListView) ] All working well. But I already have a question 1. Why my view function have a request variable, but I can call this function from urls without defining this variable? 2. Why I can't use this syntax path('/Person', PersonListView**()**)? What is wrong with this brackets? And another part of my question. But then I decided to make some refactoring - I intended to use one view both for person and companies, so I have to pass a variable … -
ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured - Scraper
When I try to run my scraper in Django I get the following error. This happened when I tried to put the scraped data into the database using the built-in Django models. traceback and error: /usr/bin/python3.6 /home/xxxxxx/Desktop/project/teo/movierater/scrap.py Traceback (most recent call last): File "/home/xxxxxx/Desktop/project/teo/movierater/scrap.py", line 7, in <module> from teo.movierater.api.models import * File "/home/xxxxxx/Desktop/project/teo/movierater/api/models.py", line 3, in <module> class Author(models.Model): File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) 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 put it in bin/activate: export DJANGO_SETTINGS_MODULE=mysite.settings Here is the code snippet from scraper.py: import django import os import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from teo.movierater.api.models import * os.environ['DJANGO_SETTINGS_MODULE'] = 'movierater.settings' django.setup() My project structure and the settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'movierater.api', ] wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'movierater.settings') application = get_wsgi_application() -
504 Gateway Time-out nginx/1.10.3 (Ubuntu)
I'm trying to host django 1.11 application on ubuntu 16.4 server using Nginx. But After running the server I'm getting 504 Gateway Time-out here is my all port log Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN 3209/redis-server 1 tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 15218/nginx -g daem tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1204/sshd tcp6 0 0 :::9200 :::* LISTEN 28810/java tcp6 0 0 :::9300 :::* LISTEN 28810/java tcp6 0 0 :::22 :::* LISTEN 1204/sshd udp 0 0 0.0.0.0:68 0.0.0.0:* 963/dhclient Nginx error.log *1 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 118.179.95.25, server: 18.136.204.142, requ$ 2019/07/24 18:13:13 [error] 15221#15221: *1 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 118.179.95.25, server: 18.136.204.142, requ$ 2019/07/24 18:20:17 [error] 15485#15485: *1 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 118.179.95.25, server: 18.136.204.142, requ$ any one have any idea about this issue? any sort of help will be appreciated -
How to compress images before uploading them to Amazon s3 using django storages and django rest framework?
I'm trying to compress the images before uploading them to the amazon s3 server, but I couldn't do it, I used 'PIL', to do it, but it didn't work This is the code I used with the library 'PIL': from io import BytesIO from PIL import Image from django.core.files import File def compress(image): im = Image.open(image) im_io = BytesIO() im.save(im_io,'PNG', quality=70) new_image = File(im_io, name=image.name) return new_image class MyModel(models.Model): file = models.FileField(blank=True, null=True, validators=[validateFileSize]) def save(self, *args, **kwargs): new_image = compress(self.file) self.file = new_image super().save(*args, **kwargs) -
Django - how do I override default date formats per locale?
We are using Django 1.11 for Speedy Net. I want to override the default values of DATE_FORMAT and MONTH_DAY_FORMAT in English, but keep the default values (or define them again) in Hebrew. So they will not be the same and will not be identical to Django's default values. In English we will have: DATE_FORMAT = 'j F Y' MONTH_DAY_FORMAT = 'j F' And in Hebrew: DATE_FORMAT = 'j בF Y' MONTH_DAY_FORMAT = 'j בF' The template currently looks like this: {% if can_view_profile and user.date_of_birth %} {% if can_view_dob_day_month or can_view_dob_year %} <tr> <th>{% if can_view_dob_day_month %}{% trans 'Birth Date' %}{% elif can_view_dob_year %}{% trans 'Birth Year' %}{% endif %}</th> <td> {% if can_view_dob_day_month and can_view_dob_year %} {{ user.date_of_birth|date:settings.DATE_FORMAT }} {% elif can_view_dob_day_month %} {{ user.date_of_birth|date:settings.MONTH_DAY_FORMAT }} {% elif can_view_dob_year %} {{ user.date_of_birth|date:'Y' }} {% endif %} </td> </tr> {% endif %} {% endif %} And I want it to display the dates in these formats in each language. How do I do it? -
Restrict or check for multiple data entries before saving in Django
How can restrict or checking data entries before saving? Example So i have different Dogs who are eating Meals with different Sizes (in Gramm) and different Foodtypes (Pork, Beef etc.). models.py class Dog(models.Model): name = models.CharField(max_length=255) meal = models.ManyToManyField('Meal') def __str__(self): return self.name class Meal(models.Model): food = models.ForeignKey('Foodtype', null=True, blank=False, on_delete=models.SET_NULL) min_g = models.PositiveIntegerField() max_g = models.PositiveIntegerField() def __str__(self): return 'Meal: %s Size: %s g to max. %s g' % (self.food, self.min_g, self.max_g ) class Foodtype(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name Every Time i enter a new Dog i also can create a new Meal. For Instance i added Harry (Dog.name) who is eating Beef (Foodtype.name) of a Size min. 200 (Meal.min_g) gramm to 300 (Meal.min_g) gramm So in my Meal Table is now a Entry of Beef, 200, 300 But Harry the Dog can have multiple Meals so i choose also Pork, 200, 300. If a other user now enters a new Dog who is eating exactly the same, the user could choose the data-point Beef, 200, 300 but he could also easily end up with a double entry by accident because it is a many-to-many relation (see following picture). On the Other Hand i need this … -
How to create User and User Profile in a single Django Admin form
I am struggling to figure out how to save User Profile for a new user created within Django Admin. I have a custom User model and a simple user Profile with OneToOneField: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(_('staff'), default=False) is_active = models.BooleanField(_('active'), default=True) ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(_('first name'), max_length=80, blank=False) last_name = models.CharField(_('last name'), max_length=80, blank=False) ... I have the following user creation form: class UserAdminCreationForm(forms.ModelForm): password1 = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField( label="Password confirmation", widget=forms.PasswordInput ) first_name = forms.CharField(label="First name") last_name = forms.CharField(label="Last name") class Meta: model = User fields = ("email",) def save(self, commit=True): user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user My admin Add user form is rendered correctly and includes fields from both User and Profile models. After saving the form, a new user and a new profile are created in the database. However, the first_name and last_name fields in profile table are empty. What I need to do to ensure that profile is saved together with the new user? -
when Deploying a django project the site doesn't load as it's not there?
I tried deploying a project on ubuntu machine on AWS but the site doesn't load as it's not there. I followed this video with slight changes as the machine was already set up and I took the ssh key and connected here's my folder structure of the project /Eyelizer /Eyelizer /App1 /App2 /Eyelizer /etc The commands I followed sudo apt-get install python-pip python-dev nginx git Y sudo apt-get update sudo pip install virtualenv git clone https://github.com/mruanova/zillow.git cd Eyelizer cd Eyelizer virtualenv venv source venv/bin/activate pip install -r requirements.txt pip install django bcrypt django-extensions pip install gunicorn cd zillow sudo vim settings.py # Inside settings.py modify these lines allowed host public IP address I for INSERT i ALLOWED_HOSTS = ['ip_address'] Save your changes and quit. ESC :wq cd .. gunicorn --bind 0.0.0.0:8000 Eyelizer.wsgi ctrl+c sudo vim /etc/systemd/system/gunicorn.service i [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/Eyelizer/Eyelizer ExecStart=/home/ubuntu/zillow/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/Eyelizer/Eyelizer.sock Eyelizer.wsgi:application [Install] WantedBy=multi-user.target ESC :wq sudo systemctl daemon-reload sudo systemctl start gunicorn sudo systemctl enable gunicorn sudo vim /etc/nginx/sites-available/Eyelizer i server { listen 80; server_name ip_address; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/Eyelizer/Eyelizer; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/Eyelizer/Eyelizer/Eyelizer... } } … -
Has anybody experience with the django-star-ratings plugin from wildfish?
I want to use a star rating system but I'm a bit overwhelmed. I found this django plugin: https://django-star-ratings.readthedocs.io/en/latest/?badge=latest%2F# I have a form where a user can rate a product. The user should be able to rate the product by clicking on the stars(with hower effects would be nice). Then this rating value (0-5) should be saved in my database. Currently I only have a field where a number can be entered and with a post request I save the data to my database. I also show all the reviews on my product page and it would be idealy when I also could use this plugin. So if there is someone that has experience with this plugin...is it possible to do all of this stuff with this plugin? Please let me know if you need more information. At the moment i use a combination of HTML CSS and JavaScript to show the stars on my product page but I think there is a more elegant slution and additionally I have no idea how I can implement that the users are capeable of clicking on the stars in the review form with my current solution.