Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display images in visual studio with D jungo and html
im trying display pictures on my html page using D jungo but its not displaying it show like this I add this code in the setting STATIC_URL = '/static/' STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static'])) MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR, 'media') and this at the end of url ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) i have html page and i wrote image code like this <img src="images/offer.jpg" alt="" /> and this is my files hope I find solution here -
I want to display only the sentences of the passed id on the screen
Template Language question. I want to pass the ID of the sentence I want to the url and display only the sentence of the passed ID on the screen. url: path('sentenceCard/<str:listName>/<int:listId>/', views.sentenceCard, name='sentenceCard') views.py: def sentenceCard(request, listName, listId): sentence = Sentence.objects.filter(Classification=listName) return render(request, 'english_note/sentenceCard.html', {'sentences':sentence, 'listId': listId}) html: <a href='#'>{{sentences.0.korean_sentence}}<br> <a href='#'>{{sentences.1.korean_sentence}}<br> Variables in Template Variables? like this? {{sentences.listId.korean_sentence}} -
Celery wont run when initiated by supervisor on aws elasticbeanstalk
I am attempting to daemonize celery beat and worker. I have no troubles running celery or beat when I ssh into my Elastic Beanstalk instance and do the following steps: cd /opt/python/current/app /opt/python/run/venv/bin/celery -A myDjangoApp beat --loglevel=INFO /opt/python/run/venv/bin/celery -A myDjangoApp beat --loglevel=INFO Tasks are scheduled and able to execute with ease. However when I run the exact same commands with supervisor I am getting an uniformative error. From looking at supervisorctl status I see the process runs for a few seconds then fails. Upon further examination the the log files show me the following error: File "/opt/python/run/venv/bin/celery", line 11, in <module> sys.exit(main()) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "/opt/python/run/venv/local/lib/python3.6/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/click/core.py", line 760, in main _verify_python3_env() File "/opt/python/run/venv/local/lib/python3.6/site-packages/click/_unicodefun.py", line 130, in _verify_python3_env " mitigation steps.{}".format(extra) RuntimeError: Click will abort further execution because Python 3 was configured to use ASCII as encoding for the environment. Consult https://click.palletsprojects.com/python3/ for mitigation steps. Listed below are my supervisor.conf and celery.sh(activates virtualenvironment and runs celery) files. Following is my supervisor.conf file. [unix_http_server] file=/opt/python/run/supervisor.sock ; (the path to the socket file) chmod=0777 ; socket file mode (default 0700) ;chown=nobody:nogroup … -
Django - view available reservation dates based on occurrence of the Event
consider we have a class that occurs 3 days a week ex: Mon,Wed,Fri from 14:00 to 18:00. I want to show only Mon,Wed,Fri and the corresponding dates - consider student wants to reserve after month, he should see the day and the date of that day. |Mon|Wed|THU|Mon|Wed|THU| |:----|:------| :-----|:----|:------| :-----| |7JUN|9JUN|10JUN|14JUN|16JUN|17JUN| I have django-recurrence and I can get the occurrence time i.e Mon,Wed,Fri How can I tie it with a date for future reservation ? Thanks in advance. -
Django admin problem with changed table column's name
I'm new to Django. Everything was fine before, but now that I've changed the name of some columns in the table, when I want to check all data inside the admin panel, It returns error. It seems that the admin still expect the previous column's names. And also the name of the models has an extra "s" at the end! For example, one of the previous column's name was "note_text" which I've changed to "text". So, what should I do now? -
Aggregating change list rows in Django using values
I'm trying to modify my model's changelist so that the user can select different filters which will sum specific fields in the model, grouping by different time frames (week, month, year). I have created a custom SimpleListFilter which correctly performs the aggregation. The problem is that it uses the values method which returns dict objects instead of my model, causing various errors. My model: class UsageReport(models.Model): install = models.ForeignKey( Installation, on_delete=models.CASCADE, help_text='The install this report is associated with' ) date = models.DateField( null=False, blank=False, default=None, help_text='The day this report\'s data is compiled for' ) players_count = models.PositiveIntegerField( null=False, blank=False, default=0, help_text='The number of new players created' ) captures_count = models.PositiveIntegerField( null=False, blank=False, default=0, help_text='The number of new captures created' ) created_at = models.DateTimeField(auto_now_add=True, null=True) My custom list filter: class DateGroupFilter(SimpleListFilter): title = 'Group By' parameter_name = 'group_by_date' def lookups(self, request, model_admin): return ( ('week', 'Week'), ('month', 'Month'), ('year', 'Year') ) def queryset(self, request, queryset): if self.value() == 'week': return queryset.annotate(week=ExtractWeek('date')).values('install', 'week').annotate( sum_players=Sum('players_count')).annotate(sum_captures=Sum('captures_count')) if self.value() == 'month': return queryset.annotate(month=ExtractMonth('date')).values('install', 'month').annotate( sum_players=Sum('players_count')).annotate(sum_captures=Sum('captures_count')) if self.value() == 'year': return queryset.annotate(year=ExtractYear('date')).values('install', 'year').annotate( sum_players=Sum('players_count')).annotate(sum_captures=Sum('captures_count')) Since each filter option returns slightly different fields (week, month, year) I tried to code a work-around which overrides the get_list_display method … -
Django - Traceback (most recent call last): File "C:\Users\Usuario\Desktop\Tinkuy\T2\T\manage.py", line 21, in <module> main()
I would like you to help me with this problem I have when opening my project in Django, I've been trying anyway and I can't find what the problem would be to run it correctly. I understand that the Django version does not influence much and I use an advanced Python version Traceback (most recent call last): File "C:\Users\Usuario\Desktop\Tinkuy\T2\T\manage.py", line 21, in <module> main() File "C:\Users\Usuario\Desktop\Tinkuy\T2\T\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'admin_interface' PS C:\Users\Usuario\Desktop\Tinkuy\T2\T> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise … -
Queryset en Django
soy nuevo en Django y quería saber si hay alguna forma de hacer filtrados de querys con multiples valores de un mismo campo de mi modelo? Follow es mi modelo donde guardo los pk de los usuarios follower y following; la consulta follows me devuelve todos los follows en los que yo figuro como follower para después poder acceder al atributo following. Después hago un lista de los pk de following para filtrar los posts hechos por usuarios con los pk de mi lista de following. Sé que entregar un lista como parametro da error, pero la plasmo para intentar explicar lo que quiero hacer que es filtrar todos los post de los usuarios que sigo. Dejo la vista que lista los posts: class PostsFeedView(LoginRequiredMixin, ListView): """Return all posts published by following.""" template_name = "posts/feed.html" ordering = ("-created") paginate_by = 30 context_object_name = "posts" def get_queryset(self): user = self.request.user follows = Follow.objects.filter(follower=user.pk) following = [] for follow in follows: following.append(follow.following) posts = Post.objects.filter(user__id=following) return posts -
How to create a product filter, when products are just foreigns keys in attribute class? (Django Ecommerce)
I'm trying to create a product filter that filters on product attributes (like this example), but I have a couple of issues: The attributes of my products are defined indirectly as a foreign key in a ProductAttributesValue class, which connects a product and an attribute key to an attribute value, i.e.: class ProductAttributesValue(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) attribute = models.ForeignKey(ProductAttributes, on_delete=models.RESTRICT) value = models.CharField( verbose_name = "value", max_length = 255 ) For now, I simply show all associated products on each product category page. Meaning attributes aren't used, yet. How do I, on the product category pages, create a filter on the product attributes, when they aren't directly defined in the Product class as a model field? Is this even the optimal way of setting up product attributes? (Categories are set up using MPTT, and I found this attribute implementation through online guides). An important note is that I want product filtering to be "hard URLs", meaning /red/ instead of ?color=red. This one requires some sort of hierarchy in the filtering, as there must be no duplicate URLs (e.g: /red/hugo-boss and /hugo-boss/red). Thanks! -
How can I pass modelformset_factory validation in Django?
I have 2 two models with a one-to-one relation as follow. class Kategori(models.Model): urun = models.CharField(db_column='Urun', max_length=255, blank=True, null=True) # Field name made lowercase. kategori = models.CharField(db_column='Kategori', max_length=255, blank=True, null=True) # Field name made lowercase. ust_kategori = models.CharField(db_column='Ust_Kategori', max_length=255, blank=True, null=True) # Field name made lowercase. urun_adi = models.CharField(db_column='URUN_ADI', max_length=255, blank=True, null=True) # Field name made lowercase. ur_id = models.CharField(db_column='UR_ID', max_length=255, blank=True, null=True) # Field name made lowercase. marka = models.CharField(db_column='MARKA', max_length=255, blank=True, null=True) # Field name made lowercase. cesidi = models.CharField(db_column='CESIDI', max_length=255, blank=True, null=True) # Field name made lowercase. miktar = models.FloatField(db_column='MIKTAR', blank=True, null=True) # Field name made lowercase. birim = models.CharField(db_column='BIRIM', max_length=255, blank=True, null=True) # Field name made lowercase. adet = models.FloatField(db_column='ADET', blank=True, null=True) # Field name made lowercase. class categoryprob(models.Model): urun = models.OneToOneField(Kategori,on_delete=models.CASCADE,related_name="prob") kategori = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. ust_kategori = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. urun_adi = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. marka = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. cesidi = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. miktar = models.FloatField(blank=True, null=True) # Field name made lowercase. birim = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. adet = models.FloatField(blank=True, null=True) # … -
Recommendations for an AutoComplete library for Django Taggit
Aside of another post I created earlier this evening relating to the configuation of Django AutoComplete Light, I just wanted to ask - What are the most recommended AutoComplete libraries out there which work with the latest version of Django? A lot of the libraries I have come across seem to be no longer maintained or are 6+ years old. I am tempted currently to continue with implementing Django AutoComplete Light although, I thought I would check here first to see if there are any other alternatives which exist? If anyone could provide me with any tips with which is the most favourable library (which works with the latest version of Django, that would be great!) Ideally, I am wanting the Select2 and tag bubbles similar to the Tagulous AutoComplete library. All suggestions are welcome. Thanks! -
How can i deploy Django to Heroku with static files
I want to publish my django application on heroku, but I am getting the error I mentioned. I researched and tried many things about it, but I could not get a positive result. remote: -----> $ python manage.py collectstatic --noinput remote: Post-processing 'css/semantic.min.css' failed! remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.7/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.7/site-packages/django/core/management/base.py", line 330, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 194, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 138, in collect remote: raise processed remote: whitenoise.storage.MissingFileError: The file 'css/themes/default/assets/images/flags.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f96f75bdf90>. remote: The CSS file 'css/semantic.min.css' references a file which could not be found: remote: css/themes/default/assets/images/flags.png remote: Please check the URL references in this CSS file, particularly any remote: relative paths which might be pointing to the wrong location. remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: … -
Не отображаются поля формы django в модальном окне bootstrap
При создании формы отображаются все поля по прямой ссылке. При связывании формы с модальным окном бутстрап(5 без использования jquery) поля не отображаются. Модальное окно открывается, но полей формы там нет. Мой первый проект на django. Возможно не корректно передаю параметры во view, либо что-то ещё не верно. Вот код модели из файла models.py: class Order(models.Model): name = models.CharField(max_length=50, verbose_name='Имя') phone = models.IntegerField(verbose_name='Номер телефона') chosen_service = models.CharField(max_length=255, verbose_name='Выбранная услуга') ordered_at = models.DateTimeField(auto_now_add=True, verbose_name='Дата отправки') agree_policy = models.BooleanField(verbose_name='Согласен с Политикой конфиденциальности') def __str__(self): return self.name class Meta: verbose_name = 'Заявка(у)' verbose_name_plural = 'Заявки' ordering = ['-ordered_at'] Код формы из файла forms.py: class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['name', 'phone', 'agree_policy', 'chosen_service'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'phone': forms.TextInput(attrs={'class': 'form-control'}), 'agree_policy': forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'flexCheckChecked', 'checked': 'checked'}), 'chosen_service': forms.HiddenInput(attrs={'id': 'chosen_service'}), } Код из view.py: def get_order(request): if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect(request.path) else: form = OrderForm() return render(request, 'blog/form.html', {'form': form}) def service_page(request, slug): advantage = Advantage.objects.all().order_by('id') detailed_service = DetailedService.objects.all().order_by('id') slug = Service.objects.values('slug') options_detailed_service = OptionsForDetailedService.objects.all().order_by('id') response_data = { 'advantage': advantage, 'detailed_service': detailed_service, 'options_detailed_service': options_detailed_service, 'slug': slug, # 'get_order': get_order, } return render(request, 'blog/service.html', response_data) Код из urls.py: urlpatterns = [ path('', main_page, … -
How to compare DateTimeFueld with Date in Django filter funtion?
In my django app I have a MessageModel with a DateTimeField "send_date". I want to filter the messages to get all messages send a certain day (Date). How do I compare the DateTimeField with a Date to get all messages send within that day. I have try with query_result= MessageLogModel.objects.filter(received_date=myDate) but it does not show the correct results. Here is the deffinition of the Model class MessageModel(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+', verbose_name=_('Destinatario'), editable=False, null=True, blank=True) subject = models.CharField(verbose_name=_("Asunto"),max_length=50) send_date = models.DateTimeField(verbose_name=_("Fecha de envío") ,auto_now_add=True) message_body = models.TextField(verbose_name=_("Mensaje")) class Meta: db_table = 'riesgo_message' managed = True verbose_name = _("Mensaje") verbose_name_plural = _("Mensajes") def __str__(self): return self.subject -
TemplateDoesNotExist at /products/login
how can i fix this PLZ enter image description here i want to delete this directory in make it instead of what you see in image to make this looking in this one C:\Users\Katsuker\PycharmProjects\first\templates TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
How to split a long line in a Django template needed for formatting?
I have a line like this in a Django template: {{ some_prefix }}{% if obj.obj_type == A_LONG_CONSTANT %}1{% elif obj.obj_type == A_LONG_CONSTANT %}2{% endif %}{{some_suffix}}: where some_prefix might be a ( or something longer, and some_suffix might be a ) or maybe even empty. I don't know how to break this up, since putting any whitespace in such a template make it look different in a browser. Think "( hi )" instead of "(hi)". Any suggestions? You might say, "Put this in python, not Django templates." However, I'm not sure how to split it up into a tag either. It depends on the template context. I see this question, but that's just renaming variable names, which might make this thing even more heinous. I think there's probably nothing to do. -
Strange Error with Django oauth-toolkit and Azure App Service. Returns 401 {"detail":"Error decoding token."} when attempting to authenticate token
Hi I am deploying an app to Azure App Service using Django Rest Framework with OAuth2 authentication handled by django-oauth-toolkit (https://github.com/jazzband/django-oauth-toolkit). Recently when trying to connect to my React frontend I have found out that I cannot successfully authorize despite having an access token. When I make a the following API call (as suggested by the documentation): curl 'http://exampleurl.azurewebsites.net/endpoint/' -H 'authorization:Bearer <sampletoken>' I get the following response: {"detail":"Error decoding token."} I cannot recreate this error locally nor can I find any information about this error anywhere online. I even searched the repository for the error to see if I could find what triggers it, unfortunately no luck. Has anyone else ever experience this or can give me some insight on what potentially occurred in my deployment to cause this? I also deleted out my old deployment and even app service to completely start from scratch and the problem persisted. -
How to set up Django Machina custom permissions
I am new to Django and python. I have been able to alter a custom user model so that the user signup form presents the user with categories and category subforums populated from Machina tables. An example would be a user choosing the category of "Biology" (category forum) and a subcategory of microbiology (subforum of the category "Biology"). When the users view the main forum page, I only them to see a couple of site wide forums and the category/subforum they chose upon registration. I am not sure how to customize Machina to accomplish this. I found the forum permissions handler.py here: https://github.com/ellmetha/django-machina/blob/a92041c2854bee6b80d418fabd4cec5caac91dc3/machina/apps/forum_permission/handler.py#L300 It seems to offer some possible ways to accomplish what I want to do, but I am not sure of a good approach. Any suggestions for customizing which forums users have access to? -
argument of NoneType is not iterable dictoinary
Below is the dictionary I am trying to access { "skipped":"", "skip_traced":"Both", "opt_out":"Both", "filters_condition":"and" } if 'Both' not in data['skip_traced']: pass The above code show me error argument of NoneType is not iterable when I reach this command. -
Django Taggit - Autocomplete Light (Guidance with configuring)
I have Taggit fully up and running and would like to configure Autocomplete Light in order to enable the Select2 dropdown when users select their preferred tags within my application. I have installed DAL, dal_select2 along with dal_queryset_sequence libraries. I already have a form created where my users can simply upload a photo, add content and a TagField. Although, the TagField currently operates as a normal text field (But the tags do successfully save through to my Taggit app) - I'm just struggling to get the Select2 dropdown working. Here are my settings (as far as the Installed Apps are concerned: Settings.py INSTALLED_APPS = [ 'core.apps.AConfig', 'users.apps.UConfig', 'crispy_forms', 'emoji_picker', 'taggit', 'dal', 'dal_select2', 'dal_queryset_sequence', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] Within my Views.py from dal import autocomplete class TagAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Tag.objects.none() qs = Tag.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs URLs.py from core.views import TagAutocomplete urlpatterns = [ url( r'^tag-autocomplete/$', TagAutocomplete.as_view(), name='tag-autocomplete', ), ] Forms.py import dal from dal import autocomplete from taggit.models import Tag class PostForm(autocomplete.FutureModelForm): tags = forms.ModelChoiceField( queryset=Tag.objects.all() ) class Meta: model = Post fields = ('__all__') … -
Is there any way to change the email scope to username scope in django
I just would like to know how to copy the email scope to the username scope in Django and for Google OAuth 2.0. -
Chained dropdown validation error. Form works
Creating a chained drop down following a tutorial. Everything works fine but it is throwing an unnecessary validation error. It is a basic 3 field form creating a person object with name, country and city. Views.py def person_create_view(request): form = PersonCreationForm() if request.method =='POST': form = PersonCreationForm(request.POST) if form.is_valid(): form.save() return redirect('person_add') return render(request, 'store/ho.html', {'form': form}) Forms.py class PersonCreationForm(forms.ModelForm): class Meta: model = Person fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id = country_id) except(ValueError, TypeError): pass elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') In forms.py line 7 where it says- self.fields['city'].queryset = City.objects.none() this line is throwing a validation error when I try to submit the form. In the tutorial they add the if/else argument and that solves the problem and error goes away. error: "Select a valid choice. That choice is not one of the available choices" In my case the error still shows up. If I ignore it and re select the city and submit, it works just fine. It is almost like having a pause at that line and the system suddenly realizes that there is more code. How do I fix … -
Is it safe to call emit_post_migrate_signal from within a Django migration?
Background My original issue that lead me to this was my desire to create a Group within a django migration (not a problem) and then also assign permissions to that Group within a migration (problem arises here). It seems that in Django that ContentTypes and Permissions are created post-migration. So migrations cannot assign Permissions to Groups because the Permissions don't exist yet. ContentType and Permission generation is triggered by the post_migrate signal, which appears to be sent automatically after all migrations have been applied. There is this work around, in which you manually call emit_post_migrate_signal from within your migration. This will generate all ContentTypes and Permissions, and then the migration can indeed successfully apply them to the Group. Question My question is: is this actually safe to do? I can't find any documentation on the emit_post_migrate_signal function, and emitting a post_migrate signal in the middle of a migration seems like a recipe for something to go wrong (either now or in the future). -
Migration from Django 2 to 3 and url with localization
I am using Django 3.2.3, Apache and Daphne. Daphne is very slow. I use Apache like a proxy to send the request to Daphne : <VirtualHost *:443> AllowEncodedSlashes On ServerName mysite.com ServerAdmin admin@gmail.com ProxyPass "/" "http://127.0.0.1:8001/" ProxyPassReverse "/" "http://127.0.0.1:8001/" Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods "GET" env=CORS Header set Access-Control-Allow-Credentials "false" env=CORS SSLCertificateFile /etc/letsencrypt/live/****/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/***/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> I launch Daphne with the command : daphne -p 8001 asgi:application When I access to my website, the log of Daphne are : 2021-06-04 21:17:17,821 INFO Adding job tentatively -- it will be properly scheduled when the scheduler starts 2021-06-04 21:17:17,865 INFO Added job "my_job" to job store "default" 2021-06-04 21:17:17,866 INFO Scheduler started 2021-06-04 21:17:17,909 INFO Starting server at tcp:port=8001:interface=127.0.0.1 2021-06-04 21:17:17,912 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2021-06-04 21:17:17,913 INFO Configuring endpoint tcp:port=8001:interface=127.0.0.1 2021-06-04 21:17:17,919 INFO Listening on TCP address 127.0.0.1:8001 2021-06-04 21:17:20,053 INFO Running job "my_job (trigger: cron[second='*/20'], next run at: 2021-06-04 21:17:20 CEST)" (scheduled at 2021-06-04 21:17:20+02:00) 2021-06-04 21:17:20,054 INFO Job "my_job (trigger: cron[second='*/20'], next run at: 2021-06-04 21:17:20 CEST)" executed successfully 2021-06-04 21:17:40,105 INFO Running job "my_job (trigger: cron[second='*/20'], next run at: 2021-06-04 21:17:40 CEST)" (scheduled at 2021-06-04 21:17:40+02:00) … -
Models Mixin ManytoMany
I want to implement in django a model mixin. I have in mixin.py: class RightsModelRelation(models.Model): user_link = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False, default=None, related_name="%(class)s_rights_user") right_to_view = models.BooleanField(default=True) right_to_change = models.BooleanField(default=False) right_to_delete = models.BooleanField(default=False) class RightsModelMixin(models.Model): rights_link = models.ManyToManyField(RightsModelRelation, default=None, related_name="%(class)s_rights_link") models.py: class Address( RightsModelMixin,models.Model): lastname = models.CharField(max_length=255, default="", ) firstname = models.CharField(max_length=255, default="", blank=True, null=True) But this don't work. Can anyone help me to implement a manytomany models mixin?