Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Comparative database metrics for different implementations of Django Model
Considering two approaches in designing Django models: 1 - Very few models, but each model has a long list of fields. 2 - Many models, each model has significantly shorter list of fields. But the models employ multi-level hierarchical one-to-many structure. Suppose they both use Postgres as the database. In general, what would be the comparative database size, latency in retrieving, processing and updating data for these two approaches? -
Django + React - struct.error: unpack requires a buffer of 4 bytes
I'm trying to runserver using python manage.py runserver and I'm getting this error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Git\commerce\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Git\commerce\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Git\commerce\venv\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Git\commerce\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Git\commerce\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Git\commerce\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Git\commerce\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Git\commerce\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Git\commerce\venv\lib\site-packages\django\contrib\auth\models.py", line 90, in <module> class Group(models.Model): File "C:\Git\commerce\venv\lib\site-packages\django\db\models\base.py", line 161, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Git\commerce\venv\lib\site-packages\django\db\models\base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "C:\Git\commerce\venv\lib\site-packages\django\db\models\fields\related.py", line 1637, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model(self, cls) File "C:\Git\commerce\venv\lib\site-packages\django\db\models\fields\related.py", line 1099, in create_many_to_many_intermediary_model 'verbose_name': … -
Django - serving static files from collect_static folder in dev
I'm having troubles figuring out how I can serve my static files from the folder where I collect all static files (for eventually in production have those served from a different server). My frontend static files are under projectroot/frontend, and the static files folder where they collect is undert projectroot/static My settings.py files looks like this for the relevant bits: STATICFILES_DIRS = [ os.path.join(BASE_DIR,'frontend'), ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") Then my urls.py (the root confs) look like this: urlpatterns = [ path(.....), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Then I run the dev server using python manager.py runserver. If I run python manage.py collectstatic, then I indeed see all the relevent files collected under projectroot/static. However, if I remove/rename the original folder (/frontend), then the static files are not served by the dev server, meaning it isn't using the /static folder. Which I would prefer to use even in dev, just because I'd rather catch any random issue right away.... What am I doing wrong? -
Memcached service is working as expected but stats items is empty
I'm using Django with docker - In my Docker-compose I created a memcached service: build: context: . dockerfile: memcached.Dockerfile ports: - '11211:11211' expose: - "11211" the Dockerfile looks like this: USER root RUN apt-get update && apt-get install -y \ telnet \ telnetd \ libmemcached-tools \ netcat USER memcache EXPOSE 11211 Now the cache location is defined in settings.py which retrieve it .ENV file : settings.py if os.getenv("CACHE_BACKEND"): cache_timeout = os.getenv("CACHE_TIMEOUT") CACHES = { 'default': { 'BACKEND': os.getenv("CACHE_BACKEND"), 'LOCATION': os.getenv("CACHE_LOCATION"), 'TIMEOUT': None } } .env CACHE_BACKEND = django.core.cache.backends.memcached.MemcachedCache CACHE_LOCATION = ***********:11211 # I covered the container name CACHE_TIMEOUT = None the actual caching function is wrapped and uses as an annotation: def caching(code_version=None): """ Decorator with argument :param code_version: code version from DB :return: real_decorator """ def real_decorator(func): """ Wrapper function that reads from the cache if the value already exists and if not then it saves it to the cache :param func: wrapped function :return: Wrapper function """ def func_wrapper(request): from django.http import HttpResponse from django.core.serializers.json import DjangoJSONEncoder from django.core.cache import cache if code_version: cache.version = code_version url = request.get_full_path() url_hash = f"{abs(hash(url))}" save_cache: bool = len(url_hash) <= 250 print(f"SAVE CACHE-----------------------{save_cache}") if save_cache: try: cache_result = cache.get(url_hash) if cache_result: … -
Displaying image URL on Django Blog Home Page
I am not able to load my blog image on landing page. Please any one can solve this issue. my HTML code inside for loop: {% for item in object_list %} <img class="rounded" src="{{item.main_image.url}}"> It gives error The 'main_image' attribute has no file associated with it. I am able to load the images in detail page by simply doing this: src="{{object.main_image.url}}"> My Model: class Item(models.Model): title = models.CharField(max_length=100) description= RichTextField(blank=True, null=True) main_image= models.ImageField(null=True, blank=True,upload_to='images/') date = models.DateTimeField(auto_now_add=True) item_slug = models.CharField(max_length=200, default=1) item_category = models.ForeignKey(Categories, default=1, on_delete=SET_DEFAULT) -
Django login and sign up in the same page
Is there a way to add login and registerati form in the same page in django? I don't know how to add signup form to loginview or importing log in form in registration page -
How to tell Django model that only one or other field must be not empty?
With Django models.Model class like that: class OrderLign(models.Model): Order = models.ForeignKey(Order,on_delete=models.CASCADE) Item = models.ForeignKey(Item, on_delete=models.RESTRICT, blank=True, default=0, null=True) Pack = models.ForeignKey(Pack,on_delete=models.RESTRICT, blank=True, default=0, null=True) I need that is possible to save OrderLign only if Item OR Pack is set, not both, and not neither. -
Update data from view context on post
I'm trying to update the context that i send to a template after receiving a post. Example of what i want to update in a template : <div id="testbox"> <a id="test ok">test</a> {{ element }} </div> The ajax for the post and update of the div : $(document).on('click', '#test', function (e) { e.preventDefault(); elementname = this.id; const request = new Request( "", {headers: {'X-CSRFToken': csrftoken, 'Content-Type': 'application/json'}} ); fetch(request, { method: 'POST', body: JSON.stringify({ pluginEdit: elementname }), mode: 'same-origin' }).then(function() { $('#testbox').load(document.URL + ' #testbox'); }); }) Extract of my views.py : if body.get("pluginEdit"): context = { //some things i send anyway 'element': body.get("pluginEdit") } return render(request, 'myapp/dashboard.html', context) I tested if it enters my "if" even though the page is already loaded, which it does, but the new part of the context doesn't reach the template when it's updated with js. Didn't found any other to do that by the way, so what am i doing wrong ? -
How to attach Datetime concentation of Django migration files names
When I run : ./manage.py makemigrations the generated migration files concatenate the model and field name together, but me I want to concatatenate Datetime on the file name generated. For example this is what I get, which I don't want : But I want something like this : This is my model : class Assessment(AllProcess, models.Model): title = models.CharField(_('Title'), max_length=100, null=False, blank=False) category = models.ForeignKey( Category, on_delete=models.DO_NOTHING, verbose_name=_('Category'), related_name='category') user = models.ForeignKey(User, on_delete=models.CASCADE) number_of_questions = models.IntegerField( _('Number of Questions'), help_text=_('Number of questions') ) time = models.IntegerField( _('Time'), help_text=_('Duration of the quiz in minutes')) score_to_pass = models.IntegerField( help_text=_('Required score to pass an assessment in %')) test = models.CharField(_('Test'), max_length=100, null=True, blank=True) difficulty = models.CharField(max_length=6, choices=DIFF_CHOICES) created_at = models.DateTimeField(auto_now_add=True) -
CSV file getting downloaded but not saved to computer
I'm working on a Django project where I create a csv file using some data that I have and then I want the user to be able to download it. The file is being created in views.py, which looks like this: def generate_csv_response(modelset, field_names, filename='export.csv'): """ Generate a CSV for all field_names in a DB model :param field_names is a dictionary which contains the model field name as a key and the CSV header display name as it's value """ response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = f'attachment; filename="{filename}"' # create the CSV writer and write a header row to the file writer = csv.writer(response) writer.writerow([v for _, v in field_names.items()]) # display names are the values # write a row of all specified fields for each model in the modelset for m in modelset: row = [getattr(m, field) for field in field_names] writer.writerow(row) # return the generated HTTP response return response class ConfigRuleViewSet(viewsets.ReadOnlyModelViewSet): queryset = ConfigRule.objects.all() serializer_class = ConfigRuleSerializer permission_classes = [permissions.IsAdminUser | ReadOnlyUser] config_rule_connector = AWSConfigRuleConnector() @action(detail=False, methods=['post'], permission_classes=[permissions.AllowAny]) def refresh(self, request): account_id = json.loads(request.body)['account_id'] if not account_id: logger.warn('Got blank account_id from ajax request: %s', account_id) if self.config_rule_connector.update(account_id): return Response(data={'updated': True, 'count': ConfigRule.objects.count()}) return Response(data={'updated': False, 'error': 'Config Rule could … -
Central position Images with CSS and HTML in django project
Working on landing page Django, trying to centre images with css, but it doesn't work for me, Im stucked, cant find any asnwer on the internet. My first project for portfolio. Please help me with this question, will be very glad. Thank you <!DOCTYPE html> {% load static %} <html lang="eng"> <! --looks good on mobile devices--> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'style.css' %}"> <head> <meta charset="UTF-8"> <title>Main page</title> </head> <body> <header class="header"> <div class="header-text" style="color:white">Follow me:</div> <a href="https://www.instagram.com/kseniia_ifbblatvia" class="header-link1">Instagram</a> <a href="https://www.tiktok.com/@super_zav" class="header-link2">TikTok</a> <a href="https://www.facebook.com/profile.php?id=100009190064504" class="header-link3">Facebook</a> <div class="images"> <img src="{% static 'tiktok.png' %}" width="100" height="100" alt="tiktok image" class="tiktok"> <img src="{% static 'insta.png' %}" width="100" height="100" alt="instagram image" class="instagram"> <img src="{% static 'facebook.png' %}" width="100" height="100" alt="facebook image" class="facebook"> </div> </header> <h1>Personal training and nutrition plan</h1> <p>Text about it</p> </body> </html> And CSS: body{ background: url(https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=889&q=80) no-repeat center center fixed; background-size: cover; } .tiktok { display: block; margin: auto; border: 2px solid white; padding: 10px; margin-right: 1070px; } .instagram { display: block; margin: auto; border: 2px solid white; padding: 10px; margin-right: 890px; } .facebook { display: block; margin: auto; border: 2px solid white; padding: 10px; margin-right: 690px; } } .header-text { height: 20%; width: 100%; display: flex; position: … -
Upload Image and parameters from android(retrofit) to django get bad request
I use API like this ; @POST("api/info/save") Call<ResponseBody> uploadMultiFile(@Body RequestBody file); and this function get images from an arraylist and add parameters to send server; private void uploadMultiFile(final String event_date, final int event_type, final int coordinate_x, final int coordinate_y) { String url = Constant.baseUrl; Coordinate coordinate = new Coordinate(); coordinate.setX(coordinate_x); coordinate.setY(coordinate_y); TokenInterceptor interceptor=new TokenInterceptor(); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(interceptor) .build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(url) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); Api service = retrofit.create(Api .class); MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM); builder.addFormDataPart("event_date", event_date); builder.addFormDataPart("event_type", String.valueOf(event_type)); builder.addFormDataPart("coordinate", String.valueOf(coordinate)); // Map is used to multipart the file using okhttp3.RequestBody // Multiple Images for (int i = 0; i < imagePathList.size(); i++) { File file = new File(imagePathList.get(i)); builder.addFormDataPart("image[]", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)); } MultipartBody requestBody = builder.build(); Call<ResponseBody> call = service.uploadMultiFile(requestBody); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Toast.makeText(MMEActivity.this, "Success " + response.message(), Toast.LENGTH_LONG).show(); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.d("d", "Error " + t.getMessage()); } }); } I got Bad Request Error. How can ı solve this problem? I use Django in my backend. This my function to get images and parameters from request. @api_view(['POST']) def eventInfoSave(request): event_date = request.data['event_date'] print(request.data) . . if … -
How to combine Django import_export with list_display in admin.py?
I'm new to Django, and I want to know how to combine import_export module with list_display in admin.py? For example: When I use list_display to disply two fields (id and IP), below codes in admin.py works fine, but I can't see the import export widgets: from django.contrib import admin from .models import SwitchModel @admin.register(SwitchModel) class SwitchAdmin(admin.ModelAdmin): list_display = ('id','IP') When I use below codes, I can see the import and export widgets, but I can no longer see the two fields (id and IP): from django.contrib import admin from .models import SwitchModel from import_export import resources from import_export.admin import ImportExportModelAdmin class SwitchModelResource(resources.ModelResource): class Meta: model = SwitchModel class SwitchModelAdmin(ImportExportModelAdmin): resource_class = SwitchModelResource admin.site.register(SwitchModel, SwitchModelAdmin) I tried to combine the two sets of codes together like below: from django.contrib import admin from .models import SwitchModel from import_export import resources from import_export.admin import ImportExportModelAdmin @admin.register(SwitchModel) class SwitchAdmin(admin.ModelAdmin): list_display = ('id','IP') class SwitchModelResource(resources.ModelResource): class Meta: model = SwitchModel class SwitchModelAdmin(ImportExportModelAdmin): resource_class = SwitchModelResource admin.site.register(SwitchModel, SwitchModelAdmin) Then I kept receiving the below Error: How can I have list_display and import_export widgets work together? Could anybody shed some light on this? -
How to loop over rows in a submitted csv file in django?
I have a Django form class SmsWebForm(forms.Form): csv_file = forms.FileField(required=False, widget=forms.FileInput(attrs={'accept': ".csv"}), label="Csv soubor s telefonními čísly") phone_number = forms.CharField(max_length=20, required=False, label="Telefonní číslo") number_format = forms.ChoiceField(label="Formát telefonního/ch čísla/el", choices=FORMATS) text = forms.CharField(max_length=300, label="Text zprávy", widget=forms.Textarea) and when it gets submitted, I expect a .csv file of the following format. eg: 777777777, 88888888, .. then I don't want to save it, only loop over the phone numbers in it and do something for each. However, I am struggling to access the contents of the .csv form file. The code in the view looks like this if request.method == "POST": form = SmsWebForm(data=request.POST, files=request.FILES) if form.is_valid(): phone_num = form.cleaned_data["phone_number"] csv_num_file = form.cleaned_data['csv_file'] orig_text = form.cleaned_data['text'] number_format = form.cleaned_data["number_format"] if not csv_num_file and not phone_num or phone_num and csv_num_file: raise forms.ValidationError("Právě jedno z polí 'telefonní číslo' nebo 'csv soubor' musí být vyplněno") if csv_num_file: with open(csv_num_file.seek(0), "r", encoding="utf-8") as f: csv_num_file.close() reader = csv.DictReader(f) for row in reader: print(row) for number in reader: ... I am "reopening" the file on the line with open(csv_num_file.seek(0), "r", encoding="utf-8") as f because when it comes in the form it is already opened but in bytes. The line for row in reader: never gets executed, the program … -
User getting logged out after external redirect in django
The user gets logged out after redirection from an external site(maybe cros-domain) to my Django app -
Seperate Resource Server(Django-oauth-toolkit) - 403 Forbidden Error(If RESOURCE_SERVER_INTROSPECTION_CREDENTIALS is used)
I run into an issue not sure if this is a bug. Any help would be appreciated. Some context: Authorization Grant Type is Resource Owner Password Credentials where the Client Type is "confidential". I used csrf_exempt decorator and protected_resource decorator for a view response function in the resource server. Django REST Framework is used. Django REST Framework v3.12.4 and Django OAuth Toolkit v1.5.0 are used. I referred to the official documentation: https://django-oauth-toolkit.readthedocs.io/en/latest/resource_server.html Testing Setup is similar to the Referenced Article using two different ports: https://medium.com/@sarit.r/simple-seperate-auth-server-and-resource-server-36a7813ea8aa Auth Server: https://github.com/pathumveyron24/Django-Auth-Server Resource Server: https://github.com/pathumveyron24/Django-Resource-Server Auth Server Settings File: """ Django settings for auth_server project. Generated by 'django-admin startproject' using Django 3.2. 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 from .config import DB_ENGINE, DB_NAME, DB_USERNAME, DB_PASSWORD, DB_HOST, DB_PORT, TIME_ZONE # 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 = 'django-insecure-h6pzc5%ovv^&5o5dg0z&e8k$7y*)fufjz%2s3t(*jick@u_u9g' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application … -
I am learning a django course on udemy and have an issue with the CSRF token part
enter image description here Why is my {% csrf_token %} being read as a text? CSRF issue is not resolved and instead I see {% csrf_token %} printed beside my input box now. -
django url redirecting not working. it appending end of requested url
i try Django 3xx with Django rest redirect to URl but its not working and i also try but not working yet views.py def redirect_shortner(request): return redirect('www.google.com') url.py urlpatterns = [ path('', redirect_shortner, name='redirect_shortner'),] so it seems perfect but.. -
I have just start study django ,i have start a small shop project ,in my product app, to enter the command makemigration i have an error occured [closed]
'how can i solve this ???? File "C:\Users\jaison varghese\AppData\Local \Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 118, in create cls = getattr(mod, cls_name) AttributeError: module 'products.apps' has no attribute 'productsconfig' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main` ` execute_from_command_line(sys.argv) File "C:\Users\jaison varghese\AppData\Loca \Programs\Python\Python38\lib\site-packages\django\ core\management\__init__.py", line 401, in execute_ from_command_line utility.execute() File "C:\Users\jaison varghese\AppData\ Local\Programs\Python\Python38\lib\site-packages\ django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\jaison varghese\AppData\Local\ Programs\Python\Python38\lib\site-packages\django\ __init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\jaison varghese\AppData\Local \Programs\Python\Python38\lib\site-packages\django\ apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\jaison varghese\AppData\Local\ Programs\Python\Python38\lib\site-packages\django\ apps\config.py", line 132, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'products.apps' does not contain a class 'productsconfig'. Choices are: 'ProductsConfig'. -
Django Test Object created is empty
I am trying to follow instructions from the Django documentation: https://docs.djangoproject.com/en/3.2/topics/testing/overview/ However when I try to create the object for the test. The object is empty?? This is my code: from django.test import TestCase, Client from django.urls import reverse from .models import ShortURL from .views import generate_shortURL, redirect, home from datetime import datetime url = "https://stackoverflow.com/" time = datetime.now() class TestURLShortener(TestCase): def setup(self): self.client = Client() obj= ShortURL.objects.create(original_url=url, short_url='zqSkSQ', time_date_created=time, count=2) obj.save() def test_creating_short_URL_POST(self): """ Test to create short Urls """ short_url_from_db = ShortURL.objects.all() print(f'short_url_from_db : {short_url_from_db}') response = self.client.post(reverse('generate_shortURL'), data={'original_url': url}) generated_short_url = response.context["chars"] self.assertEquals(generated_short_url, 'afasdf') This is the results when I run the test: short_url_from_db prints out this <QuerySet []> instead of the object I wanted it to print out from the setup function. How can I get the object I created to use in this test? -
Django is not displaying image
I am trying to build an e-commerce website using python's Django framework as part of a practice project. However, I am not being able to display my product's image on my landing page. Django version: 3.2.4 models.py: class Listing(models.Model): title = models.CharField(max_length=100) price = models.FloatField() description = models.TextField() image = models.ImageField(upload_to="auctions/images/", default="") settings.py: STATIC_URL = '/static/' # Managing media MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py: from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("", include("auctions.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def index(request): listings = Listing.objects.all() return render(request, 'auctions/index.html', { "listings": listings }) index.html {% extends "auctions/layout.html" %} {% load static %} {% block body %} <h2>Active Listings</h2> {% for listing in listings %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{% static listing.image %}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ listing.title }}</h5> <p class="card-text">{{ listing.description }}</p> <p class="card-text">Price - {{ listing.price }}</p> <a href="#" class="btn btn-primary">Bid</a> </div> </div> {% endfor %} {% endblock %} I am only getting the alt attribute for the img tag. -
How to keep some data in django testing?
As you know django give you clear database in testing, but I have a ready() method that create some data for me and I need to query these data in my tests. class YourAppConfig(AppConfig): default_auto_field = 'django.db.models.AutoField' name = 'Functions.MyAppsConfig' def ready(self): from django.contrib.auth.models import Permission from django import apps from django.contrib.contenttypes.models import ContentType try: Permission.objects.get_or_create(....) MyOtherModel.objects.get_or_create(....) except: pass class TestRules(APITestCase): def test_my_model(self): .... x = MyOtherModel.objects.filter(....).first() # x = None # <=========== problem is here ========= I need to see the data that I created in the ready method .... -
django deployment on Heroku KeyError: 'MAILGUN_API_KEY'
I m using cookie cutter but did not select Heroku deployment in selection list when creating app. but now, I want it on Heroku. I've this error: File "/app/.heroku/python/lib/python3.8/os.py", line 675, in __getitem__ remote: raise KeyError(key) from None remote: KeyError: 'MAILGUN_API_KEY' remote: During handling of the above exception, another exception occurred: Traceback (most recent call last): remote: File "manage.py", line 31, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 231, in fetch_command remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 991, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 783, in exec_module remote: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed remote: File "/tmp/build_3a322b24/config/settings/production.py", line 132, in <module> remote: "MAILGUN_API_KEY": env("MAILGUN_API_KEY"), remote: File "/app/.heroku/python/lib/python3.8/site-packages/environ/environ.py", line 123, in __call__ … -
How can I add a Bootstrap modal that contains a model form into another Django model form?
I have a model form "NewJobEntryForm" which creates a new JobEntry, and in that JobEntry form, users can select ServiceItemStats objects that will be associated by a many-to-many relationship. I would like to enable the user to create new ServiceItemStats objects if they need to, without leaving the JobEntry form. For this, I would like to use a Bootstrap modal that would hold a "NewServiceItemStatsForm", but I am not sure how to go about doing this. Any help would be appreciated. My code is: Models.py class JobEntry(models.Model): # PK: id - automatically assigned by Django. job_entry_date_time = models.DateTimeField(default=timezone.now) job_date = models.DateField(blank=True, null=True) job_checked_in = models.BooleanField() job_checked_out = models.BooleanField(default=False) job_priority = models.IntegerField() job_time_estimation = models.IntegerField(blank=True, null=True) job_comments = models.TextField(max_length=200, blank=True, null=True) job_parts_instock = models.BooleanField(default=False) job_started = models.BooleanField(default=False) job_finished = models.BooleanField(default=False) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) #One-to-one relationship customer = models.ForeignKey(Customer, on_delete=models.CASCADE) #One-to-one relationship serviceBay = models.ForeignKey(ServiceBay, on_delete=models.CASCADE, blank=True, null=True) #One-to-one relationship serviceItemStats = models.ManyToManyField(ServiceItemStats, blank=True) #Many-to-many relationship class ServiceItemStats(models.Model): service_stats_name = models.CharField(primary_key=True, max_length=20) service_stats_estimate_duration = models.IntegerField() # Many-to-many relationship with JobEntry. def __str__(self): return self.service_stats_name Forms.py class NewJobEntryForm(ModelForm): class Meta: model = JobEntry fields = ['vehicle', 'customer', 'job_date', 'job_checked_in', 'job_priority', 'job_comments', 'job_parts_instock', 'serviceItemStats'] widgets = { 'job_date' : forms.DateInput(format=('%m/%d/%Y'), attrs={'class':'form-control', 'placeholder':'Select a … -
Passing an Object into Include Template Tag Django
I am developing a website in django and I have encountered a problem. I am using an 'include' template tag and I am trying to pass an object into the tag. But whenever I pass it in, it is passing in the dunder str method of the object. {% include 'function/comment' object=answer %} 'answer' is the object I want to pass in (fyi it is a model object) Instead of passing 'answer' as an object it is passing the dunder str method. Is there a way to solve this? Thanks in advance.