Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Powershell file .ps1
I am stuck on a problem. I have a python application with a Django server and fronted in React. I run the Django and React server via a .ps1 file On the other hand, when I relaunch my application I open a new CMD window for Django and React I can't find a solution to kill the windows that are already open. code python3 to run file .ps1 {p = subprocess.run('powershell.exe -ExecutionPolicy RemoteSigned -file"entrypoint.ps1"', stdout=subprocess.PIPE, shell=True, timeout=30) } code powershell (.ps1) {Start-Process -FilePath 'venv/Scripts/python.exe' -ArgumentList "./manage.py runserver" Start-Process -FilePath 'venv/Scripts/python.exe' -ArgumentList "main.py" Start-Process 'npm' -ArgumentList "start" -WorkingDirectory "../prg_Frontend"} -
problems making the formset dynamic
I need urgent help. my formset is not visible when I click the '+' button I suspect that my view is badly done, even though the fields are visible, when increasing the extra from views, the change is not seen in the button. The problem is not in javascript since I already did tests. They can help me to check my code. I'm new at this additionally I also want to mention that whenever I put my code in html here in stackoverflow I see some strange spaces on the left side. It doesn't happen to me like this when I put javascript or python presupuestos-forms.html <section> <div> <form method="POST"> {% csrf_token %} <div class="row"> <div class="col-12"> <div class="card"> <div class="card-body"> <h4 class="card-title">Partes</h4> <p class="card-title-desc">Agrega las partes que se incluirán</p> <div class="table-responsive"> <table class="table table-bordered table-nowrap align-middle"> <thead class="table-info"> <tr> <th scope="col">Código</th> <th scope="col">Descripción</th> <th scope="col">Cantidad</th> <th scope="col">Precio Unitario</th> <th scope="col">Precio Total</th> <th scope="col">Libre de Impuestos</th> <th scope="col">Agrega Fila</th> </tr> </thead> <tbody> <tr> <td> {{presupuestosparteform.codigo}} </td> <td> {{presupuestosparteform.descripcion}} </td> <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> {{presupuestosparteform.total_price}} </td> <td> <div> {{presupuestosparteform.tax_free}} </div> </td> <td> <input type="button" class="btn btn-block btn-default" id="add_more" value="+" /> </td> </tr> <tr id="formset"> {{ formset.management_form }} {% … -
Django Elastic Beanstalk 502 Error Gunicorn No module named application
I have a django app and im trying to deploy it into aws elastic beanstalk but im getting 502 error from nginx, I have gunicorn installed and listed on my requirements.txt file. Checking the logs i see the following: Nov 17 20:35:22 ip-172-31-12-36 web: [2021-11-17 20:35:22 +0000] [3510] [INFO] Starting gunicorn 20.1.0 Nov 17 20:35:22 ip-172-31-12-36 web: [2021-11-17 20:35:22 +0000] [3510] [INFO] Listening at: http://127.0.0.1:8000 (3510) Nov 17 20:35:22 ip-172-31-12-36 web: [2021-11-17 20:35:22 +0000] [3510] [INFO] Using worker: gthread Nov 17 20:35:22 ip-172-31-12-36 web: [2021-11-17 20:35:22 +0000] [3516] [INFO] Booting worker with pid: 3516 Nov 17 20:35:22 ip-172-31-12-36 web: [2021-11-17 20:35:22 +0000] [3516] [ERROR] Exception in worker process Nov 17 20:35:22 ip-172-31-12-36 web: Traceback (most recent call last): Nov 17 20:35:22 ip-172-31-12-36 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Nov 17 20:35:22 ip-172-31-12-36 web: worker.init_process() Nov 17 20:35:22 ip-172-31-12-36 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/gthread.py", line 92, in init_process Nov 17 20:35:22 ip-172-31-12-36 web: super().init_process() Nov 17 20:35:22 ip-172-31-12-36 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process Nov 17 20:35:22 ip-172-31-12-36 web: self.load_wsgi() Nov 17 20:35:22 ip-172-31-12-36 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi Nov 17 20:35:22 ip-172-31-12-36 web: self.wsgi = self.app.wsgi() Nov 17 20:35:22 ip-172-31-12-36 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi Nov … -
How to pass form into template and save it? Django
Hello I have a question how can I pass a form into HTML template and save it in class based view? As you see in views.py I have made Item.objects.create after Post request but is it a good practice if Django provides forms? Form: class itemCreationForm(ModelForm): name = forms.CharField() class Meta: model = Item fields = ['name'] views.py: class Home(ListView): model = Item template_name = 'home/todo.html' form_class = itemCreationForm def post(self, request): item = self.request.POST.get('item') Item.objects.create(name=item) return HttpResponse(f'Post! {item}') -
How to POST and PUT data using fetch api?
Below is the html file with the all the following in <script It receives the value of game_title by getting the element id of the input which is filled out in the form. It correctly receives the information that the user enters in the forms async editGame(game){ var game_title = document.getElementById("edit_game_title").value; var age_rating = document.getElementById("edit_age_rating").value; var genre = document.getElementById("edit_genre").value; var game_release_date = document.getElementById("edit_game_release_date").value; alert(game_title) // ajax request to edit that game let response = await fetch(game.api, { method: "PUT", body: JSON.stringify({ Title : game_title, AgeRating : age_rating, Genre : genre, ReleaseDate : game_release_date, }), headers:{ "Content-Type": "application/json", "X-CSRFToken": document.querySelector("[name=csrfmiddlewaretoken").value, } }); if (response.ok){ game.editing = false; } else{ alert("Failed to edit") } }, async addGame(games) { var game_title = document.getElementById("game_title").value; var age_rating = document.getElementById("age_rating").value; var genre = document.getElementById("genre").value; var game_release_date = document.getElementById("game_release_date").value; // ajax request to add a game if (confirm(`Are you sure you want to add ${game_title}?`)) { let response = await fetch(games.api, { method: "POST", body: JSON.stringify({ Title : game_title, AgeRating : age_rating, Genre : genre, ReleaseDate : game_release_date, }), headers: { "X-CSRFToken": document.querySelector("[name=csrfmiddlewaretoken").value, }, }) if (response.ok){ //this.games = this.games.filter(g => g.id != game.id) // game was added! this.games = this.games alert("added game") } else{ alert("Failed to … -
django in production refuse to show error details written with restframewortk status
I have used django rest framework.status to return some custom error details and it works fine in test mode. but when I lunched my code on server it just return error code 500 internal error. I'm using django, django-rest-framework, react-redux, gunicorn and nginx. Has anyone had the same problem and know how to fix it? I didn't know what part of my code to include but if you need any details just tell me. -
Django DateTimeField ValidationError: value has an invalid format (different question:))
The field is simple: timestamp=DateTimeField(primary_key=True) When I check the value of DATETIME_INPUT_FORMATS, it's standard: ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M'] Regardless of me setting USE_L10N to True or False it outputs the timestamps in this format: "June 12, 2021, 2:40 a.m.". And most interesting, when I try to delete an entry, it gives me this exception: Traceback (most recent call last): File "/home/pooh/venv39/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/pooh/venv39/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1739, in changelist_view response = self.response_action(request, queryset=cl.get_queryset(request)) File "/home/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1406, in response_action queryset = queryset.filter(pk__in=selected) File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/query.py", line 941, in filter return self._filter_or_exclude(False, args, kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) … -
Removing field from JSON response
I would like to remove a field from Json response in Django REST framework. I'm trying to do this, but it wont help, because it's basic serializer method field(created in serializer, without models and migrations), and its not inside validated data. if validated_data.get('my_field') and self.context['request'].public_api: validated_data.pop('my_field', None) Any ideas? -
Annotate a Django Queryset Using a 'related_name' Across a ManyToMany Relationship (NO 'Count', 'Avg', 'Max', ...)
I have models in my code similar to the following: class CompanyProject(models.Model): """ This class holds project related information read in from the 'project' custom 'manage.py' command. """ project_number = models.IntegerField(blank=False, null=False, unique=True) project_worktype = models.CharField(blank=True, max_length=255, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=False, null=False) updated_at = models.DateTimeField(auto_now=True, blank=False, null=False) last_seen = models.DateField(blank=False, null=False) def get_project_subtypes(self): subtypes = self.project_subtype.all() return [ subtype.project_subtype for subtype in subtypes ] class Meta: ordering = ['project_number'] class CompanySubType(models.Model): class CompanySubTypeChoices(models.TextChoices): G1A = '1A', _('1A') G1B = '1B', _('1B') G2A = '2A', _('2A') G2B = '2B', _('2B') G3A = '3A', _('3A') G3B = '3B', _('3B') company_project = models.ManyToManyField(CompanyProject, related_name='project_subtype') project_subtype = models.CharField(blank=False, choices=CompanySubTypeChoices.choices, max_length=2, null=False) class ListEntry(models.Model): list_project = models.OneToOneField(CompanyProject, on_delete=models.CASCADE, related_name='list_project') list_reviewer = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='+') I would like to return a set of annotated ListEntry objects annotated with a list of ALL of the project subtypes identified with the ListEntry project. Eventually, I need to be able to pass this annotated data to a Django REST Framework serializer but I need to get the annotation working like I want it to first. My problem is that I can annotate just fine doing something like this: list_entry_qs = ListEntry.objects.prefetch_related('list_project', 'list_reviewer').annotate(subtypes=F('list_pmatt__project_subtype__project_subtype')).all() and it works just fine. The … -
Big files and 502s with nginx, uwsgi, and ELB
I'm having difficulty trying to debug why I'm getting 502s on uploading large files. I keep getting errors that the keepalive dies eg When I check the nginx logs: 2021/11/17 19:17:04 [info] 33#33: *82 client 10.0.10.148 closed keepalive connection 2021/11/17 19:15:45 [info] 32#32: *104 client 10.0.20.96 closed keepalive connection When I check the uwsgi/app logs, I don't see much. I get occasional OS errors like Wed Nov 17 17:28:37 2021 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request but I don't think they're related. I also get worker signal 9 errors but I think some may be memory errors DAMN ! worker 3 (pid: 19) died, killed by signal 9 :( trying respawn ... If these are memory issues on the uswgi workers, how do I go about increasing the memory per process? nginx.conf: http { access_log /dev/stdout; include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $upstream_addr ' '"$http_referer" "$http_user_agent"'; access_log /var/log/nginx/access.log main; client_max_body_size 900M; proxy_connect_timeout 600; proxy_read_timeout 600; proxy_send_timeout 600; client_header_timeout 1200; client_body_timeout 1200; server { listen 80 default_server; listen [::]:80 default_server; server_name nginx localhost 0.0.0.0 127.0.0.1 18.144.134.122; charset utf-80; root /var/www; index index.html; gzip on; gzip_static on; gzip_types … -
Django and Mysql high CPU. (optimisation)
I have an application that uses the Django rest framework to expose API endpoints, and the application is receiving ±1000 requests per second (not sure about the number). The Django app and MySQL DB were both in shared web hosting, but since the beginning of this week, the server is experiencing high CPU issues, and after TSing found that the python processes are what causing the issue. So I moved the app to a 2 vCPU, 4G Ram, and SSD hard disk VPS. After moving all data and doing the needed configuration, the app is running but another high CPU issue appeared but this time by Mysqld service, and on avg, it is 150%. When checking the mytop command output, the qps is varying between 100 and 200, while in fewer traffic times it is 65 ( and I’m not sure if it should be less during fewer traffic times given that the traffic has significantly dropped) All requests are looking for the same data and checking if there is an update, I was thinking about changing the methodology to webhook based but the data on my server updates every 30 seconds at most so I thought it won’t do … -
Get .csv values without saving it
Right now I am uploading a .csv file via a model form, saving it in a model and then reading/saving all the values from the .csv to another model. The .csv isn't needed after I get all the values into the other model so I have been trying to find a way to just read the .csv and get the values without saving it into the model. Below is the basics of my view. I appreciate any tips. def ncaab_csv(request): form = CsvUpload(request.POST or None, request.FILES or None) if request.method == "POST": if form.is_valid(): form.save() # Get the submitted csv file games_file = Csv.objects.get(games_entered=False) with open(games_file.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i == 0: pass else: try: game = NCAABGame.objects.get(name__name=row[1], updated=False, date=today) All NCAABGame fields here... game.save() return redirect(reverse('ncaab_games')) else: messages.error(request, "Failed to save file.") else: template = 'management/ncaab/ncaab_csv.html' context = { 'form': form, } return render(request, template, context) -
"ModuleNotFoundError: No module named 'apps.cashpool'; 'apps' is not a package"
I have a bunch of apps in my Django project which worked smoothly to date. I added another app universe via manage.py startapp as always and now it returns ModuleNotFoundError: No module named 'apps.cashpool'; 'apps' is not a package whenever and wherever I try to import modules. I have all apps listed in my settings.py manage.py check doesn't return any errors All apps have an __init__.py There is no trailing comma missing in settings.py Project structure (I didn't change the structure at all): -
AttributeError at /products/register type object 'address' has no attribute 'USERNAME_FIELD'
Write a code for register function user. here i have auth_user model one-to-one connection with address model. While i am open register.html this error occurs i am refering lots of tutorial & question answer sessions but this is not yet solved. please help to solve it. Error Message AttributeError at /products/register type object 'address' has no attribute 'USERNAME_FIELD' Request Method: GET Request URL: http://127.0.0.1:9000/products/register Django Version: 3.2.9 Exception Type: AttributeError Exception Value: type object 'address' has no attribute 'USERNAME_FIELD' Exception Location: C:\Users\sujit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\forms.py, line 103, in init Python Executable: C:\Users\sujit\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 Python Path: ['C:\Users\sujit\OneDrive\Desktop\project\django', 'C:\Users\sujit\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\sujit\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\sujit\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\sujit\AppData\Local\Programs\Python\Python39', 'C:\Users\sujit\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\sujit\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Wed, 17 Nov 2021 17:13:50 +0000 -
Django and chartjs, Why can't I display same three chart on home page
I want to display a 3 x chart on the home page. The problem is that only one is displayed If I remove first {% block%} from first div, chart will be displayed from the second div. How do I view all three charts? Thanks for every reply. in base.html <div class="card1"> {%block chart1%}{%endblock%} </div> <div class="card2"> {%block chart2%}{%endblock%} </div> <div class="card3"> {%block chart3%}{%endblock%} </div> in index.html {% block chart1 %} <div class="charts"> <canvas id="myChart"></canvas> <script> const ctx = document.getElementById('myChart'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: [ {% for x in data %}'{{ x.name }}',{% endfor %}, {% for y in data %}'{{ y.numbers }}',{% endfor %},], datasets: [{ label: '# of Votes', data: [ {% for x in data %}{{ x.name2 }},{% endfor %}, {% for y in data %}{{ y.name2 }},{% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', ], borderWidth: 5 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </div> {% endblock chart1 %} {% block chart2 %} Here's the code from chart1 {% endblock chart2%} {% block chart3 %} … -
Django inlineformset issue
Helo, i want to ask you, how to add dynamic forms with formsets, i have this code , it works correctly but it dont send data to database, can you tell me how to work with this, what do .empty_form part in this formset enter code here <form id="post_form" method="post" action="{% url 'home' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <a href="javascript:void(0)" id="add_form">Add Form</a> <br><input type="submit" name="submit" value="Submit" /> {{ form_images.management_form }} </form> <script src="{% static 'multiimages/js/main.js' %}"></script> <script> var form_count = {{form_images.total_form_count}}; $('#add_form').click(function() { form_count++; var form = '{{form_images.empty_form.as_p|escapejs}}'.replace(/__prefix__/g, form_count - 1); $('#post_form').prepend(form) $('#id_form-TOTAL_FORMS').val(form_count); }); </script> views class ItemCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): template_name = "multiimages/index.html" success_message = 'Item successfully added!' form_class = ItemForm success_url = "posts" model = Item def get_context_data(self, **kwargs): context = super(ItemCreateView, self).get_context_data(**kwargs) context['form_images'] = ItemImageFormSet() if self.request.POST: context['form_images'] = ItemImageFormSet(self.request.POST, self.request.FILES) else: context['form_images'] = ItemImageFormSet() return context def form_valid(self, form): context = self.get_context_data() form_img = context['form_images'] with transaction.atomic(): form.instance.user = self.request.user self.object = form.save() if form_img.is_valid(): form_img.instance = self.object form_img.save() return super(ItemCreateView, self).form_valid(form) -
Check if email already exist in database
In my django account app I want to check if inputed email exist in database (basic django db.sqlite3). forms.py: from django import forms from django.contrib.auth.models import User class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Hasło', widget=forms.PasswordInput) password2 = forms.CharField(label='Powtórz hasło', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'first_name', 'email') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Hasła nie są identyczne.') return cd['password2'] views.py: def register(request): if request.method == "POST": user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Creating new user object, without saving in database new_user = user_form.save(commit=False) # Setting new password new_user.set_password( user_form.cleaned_data['password']) # Saving user object new_user.save() return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form}) Now when i enter the same email for another user, form creates that user. I think is it possible to make this in that way? 1). make email as variable like password and password2 2). remove email from meta 3). create method clean_email() with checking if email exist in db if not raise error I don't know how to get to emails in db Thanks for all help! -
How can I implement the same widget that Django uses to ManyToMany fields in the admin page?
My models: class Ingredient(models.Model): BASE_UNIT_CHOICES = [("g", "Grams"), ("ml", "Mililiters")] CURRENCY_CHOICES = [("USD", "US Dollars"), ("EUR", "Euro")] ingredient_id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) base_unit = models.CharField(max_length=2, choices=BASE_UNIT_CHOICES) cost_per_base_unit = models.FloatField() currency = models.CharField( max_length=3, choices=CURRENCY_CHOICES, default="EUR") def __str__(self): return self.name class RecipeIngredient(models.Model): quantity = models.FloatField() ingredient_id = models.ForeignKey(Ingredient, on_delete=models.CASCADE) def __str__(self): return f"{self.quantity} / {self.ingredient_id}" class Recipe(models.Model): recipe_id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) ingredients = models.ManyToManyField(RecipeIngredient) date_created = models.DateTimeField('Date Created') def __str__(self): return f"{self.name}, {self.ingredients}" When I use the admin page, it has this + button that allows me to create new ingredient/quantity combinations like this But when I try to use it from a form in my code it looks like this Here is my form code: class AddRecipeForm(forms.ModelForm): class Meta: model = Recipe fields = ['name', 'ingredients', 'date_created'] -
django.contrib.admin.sites.AlreadyRegistered: The model BookInstance is already registered in app 'catalog'
For some reason I can't run my webapp because of this code it is showing this error: django.contrib.admin.sites.AlreadyRegistered: can anyone help me what should I do? class BookInstance(models.Model): """Model representing a specific copy of a book (i.e. that can be borrowed from the library).""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library') book = models.ForeignKey('Book', on_delete=models.RESTRICT, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='Book availability', ) class Meta: ordering = ['due_back'] def __str__(self): """String for representing the Model object.""" return f'{self.id} ({self.book.title})' @property def is_overdue(self): if self.due_back and date.today() > self.due_back: return True return False -
psycopg2-binary installation into a virtual environment fails when trying to compile source code
I am trying to install psycopg2-binary into my Django project. I am using a virtual environment and the command I'm running is pip install psycopg2-binary However, I'm getting a massive error message, the gist of it is this: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. But, hey, I'm installing exactly 'psycopg2-binary' Why am I getting all this mess? -
How can I display images from my Django DB?
Currently, although it may not be best practice, I have images stored in my django database and want to fetch them to display in a gallery page. However, I cannot get the image to display at all, which I think is because it does not arrive at the correct path. <img src ="{% static 'img/' object.image %}"> This code is to try and arrive at the correct directory for the uploaded image which is \AFA\src\artForAll\static\img Also object.image comes from this model class GalleryPost(models.Model): title = models.CharField(max_length=120) description = models.TextField(blank =True, null=True) artist = models.CharField(max_length=120) featured = models.BooleanField(default= False) image = models.ImageField(null = True, blank = True, upload_to = "static/img/") All of the other fields here work and I can see that the image is being uploaded to the correct place. -
Need Assistance with Raw MySQL Query in Django or Calling a View in Django that Does Not Error from No Primary Key Inclusion
I am working on a project that deals with capacity and resource planning for a small business. I have built an app using a Django that facilitates collection of data for assigned tasks and target goals and then compares that to user entries made against tasks assigned to them. The query for the Finance department should display as two tables on a single page. After researching this topic for some time, I have found two ways that sound best for dealing with the specific SQL queries needed: Use the Raw SQL option for Django to create the lists. Create a View in MySQL and set the model in the model file as a managed=False model. There are several problems impeding progress with this query that seem to stem from the need query sets have in Django to have a primary key value. SQL Queries The following are the two queries as they are executed successfully in the MySQL Workbench: SELECT projects.project_number AS 'project', projects.start_date AS 'start_date', projects.target_date AS 'target_date', SUM(tasks.target_hours) AS 'target_hours', SUM(activities.hours) AS 'billed_hours', (SUM(tasks.target_hours) - SUM(activities.hours)) AS 'remaining_hours' FROM activities INNER JOIN tasks ON activities.task_id = tasks.id INNER JOIN projects ON tasks.project_id = projects.id GROUP BY projects.project_number, tasks.task_number, … -
Django page that uploads csv in memory and sends off json to api
I am attempting to use django to make a site that interacts with an api for the user. The first page of the site needs to be a csv upload, that then parses the data into a json format and sends if off to the api. I've gone through the django tutorial for the polls app, and have a minimal understanding of django. But it is really overwhelming. I was able to get the csv upload from this site working: csv upload But that stores the data to a model. (Which may ultimately be ok.) But I was thinking that I could just upload the csv and convert it straight to a json without storing it? I think I'm just looking for some direction on how to have a simple upload where the upload buttom is just a submit that triggers the csv ingestion, formatting, and api request. The only thing I think I need to store is the response from the request. (It returns an ID that I need in order to retrieve the results through a different API call.) I also notices that the current view only updates the table with new rows. So I was able to … -
Django and Tailwind 'TemplateDoesNotExist' error
I am following this tutoiral: https://www.ordinarycoders.com/blog/article/django-tailwind I have a django project called 'project' with two apps in it 'app' and 'main'. I'm trying to load 'main > template > main > home.html'. but I get this error: Internal Server Error: / Traceback (most recent call last): File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\project\main\views.py", line 5, in homepage return render(request = request, template_name="main/home.html") File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: main/home.html [17/Nov/2021 11:49:03] "GET / HTTP/1.1" 500 80436 Following the tutorial, I have in my 'settings.py': """ Django settings for project project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = … -
AttributeError at /products/register type object 'address' has no attribute 'USERNAME_FIELD'
Write a code for register function user. here i have auth_user model one-to-one connection with address model. i am refering lots of tutorial & question answer sessions but this is not yet solved. please help to solve it. aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaagdddddddddddddfdgnfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdnnnnnnnnnnnnnnnnnnnnn forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from . models import address class RegisterForm(UserCreationForm): first_name = forms.CharField( max_length=100, required = True, help_text='Enter First Name', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), ) last_name = forms.CharField( max_length=100, required = True, help_text='Enter Last Name', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}), ) email = forms.EmailField( max_length=100, required = True, help_text='Enter Email Address', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), ) house_name = forms.CharField( max_length=200, required = True, help_text='Enter House Name', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'House name'}), ) town = forms.CharField( max_length=200, required = True, help_text='Enter Town', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Town'}), ) post_office = forms.CharField( max_length=200, required = True, help_text='Enter Post Office', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Post Office'}), ) pincode = forms.CharField( max_length=200, required = True, help_text='Enter Pincode', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Pin Code'}), ) district = forms.CharField( max_length=200, required = True, help_text='Enter District', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'District'}), ) land_mark = forms.CharField( max_length=200, required = True, help_text='Enter Landmark', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Landmark'}), ) phone = forms.CharField( max_length=200, required …