Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a view and nested urls correctly in Django for quiz app so that every question was on a new page?
I'm making a quiz app and can't figure out this problem. I understand how a ListView works on one page, but I need to make every question of the quiz with answers to apper on a new page (I mean, one question with possible answers and "next" button), and after that to show the results. I'm trying to make a nested urls, but it doesn't work. Maybe there are a better ways to do it? My models: class Quiz(models.Model): name = models.CharField(max_length=100) image = models.ImageField(blank=True, null=True, upload_to='images/quiz/') class Meta: verbose_name_plural = 'Quizzes' def __str__(self): return self.name class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions') question = models.CharField(max_length=255) def __str__(self): return self.question class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=255) is_correct = models.BooleanField() def __str__(self): return self.answer I tryed this view: class QuestionView(DetailView): model = Question template_name = 'question.html' def get_object(self, queryset=None): queryset = Question.objects.filter(quiz=self.kwargs['question_pk']) return queryset def get_context_data(self, **kwargs): context = super(QuestionView, self).get_context_data(**kwargs) context['quiz'] = Quiz.objects.get(pk=self.kwargs['quiz_pk']) return context And this url: urlpatterns = [ re_path(r'^quiz/(?P<quiz_pk>[0-1000])/(?P<question_pk>[0-1000])/$', QuestionView.as_view(), name='question'), ] I don't even know where to start so any advice is highly appreciated. Thank you. I'm trying to use nested urls, but I'm not sure it's the right way -
Updating the value of a model variable remotely
I want to update the value of inventory in 'Item' whenever I create a 'PurchaseItem' object. model.py(1): class PurchaseItem(models.Model): product = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) Here, quantity represents no. of items purchased so when I create this object; I want inventory value to be updated here: model.py(2): class Item(models.Model): title = models.CharField(max_length=100) model = models.CharField(max_length=100) sku = models.CharField(max_length=100) ean = models.CharField(max_length=100) price = models.FloatField() inventory = models.IntegerField() -
Django and pylintt: inconsistent module reference?
Possibly because of my noobness, I can't get pylint and django management commands to agree about how to import files in my project. Setup # venv cd $(mktemp -d) virtualenv venv venv/bin/pip install django pylint pylint-django # django venv/bin/django-admin startproject foo touch foo/__init__.py touch foo/foo/models.py # management command mkdir -p foo/foo/management/commands touch foo/foo/management/__init__.py touch foo/foo/management/commands/__init__.py echo -e "import foo.models\nclass Command:\n def run_from_argv(self, options):\n pass" > foo/foo/management/commands/pa.py # install perl -pe 's/(INSTALLED_APPS = \[)$/\1 "foo",\n/' -i foo/foo/settings.py # testing venv/bin/python foo/manage.py pa venv/bin/pylint --load-plugins pylint_django --django-settings-module=foo.foo.settings --errors-only foo Result You'll note that manage.py is happy with import foo.models, but pylint isn't: ************* Module foo.foo.management.commands.pa foo/foo/management/commands/pa.py:1:0: E0401: Unable to import 'foo.models' (import-error) foo/foo/management/commands/pa.py:1:0: E0611: No name 'models' in module 'foo' (no-name-in-module) If I change it to import foo.foo.models, pylint passes but manage.py breaks: ... File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/tmp/tmp.YnQCNTrkbX/foo/foo/management/commands/pa.py", line 1, in <module> import foo.foo.models ModuleNotFoundError: No module named 'foo.foo' What am I missing? -
How to make forigen key relationship in django
Hi I have two table in my django database which have one to many relation. In one table I have some data and I want to copy all that data to the next one code is below. forms.py: I want the exec_summary value from NewProductForm to NewReportForm. class NewProductForm(forms.ModelForm): exec_summary = forms.BooleanField(required=False) scope = forms.BooleanField(required=False) isms = forms.BooleanField(required=False) methodology = forms.BooleanField(required=False) recommendation = forms.BooleanField(required=False) class Meta: model = DB_Product fields = ('name', 'description', 'exec_summary', 'scope','isms','methodology','recommendation') widgets = { 'name': TextInput(attrs={'class': 'form-control', 'type': "text", 'required': "required", 'placeholder': "Product Name"}), 'exec_summary' : forms.BooleanField(), 'scope' : forms.BooleanField(), 'isms' : forms.BooleanField(), 'methodology' : forms.BooleanField(), 'recommendation' : forms.BooleanField(), } class ProductModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "%s" % obj.name class NewReportForm(forms.ModelForm): product = ProductModelChoiceField(queryset=DB_Product.objects.all(), empty_label="(Select a product)", widget=forms.Select(attrs={'class': 'form-control'})) P_executive_summary = forms.BooleanField(required=False) class Meta: today = datetime.date.today().strftime('%Y-%m-%d') nowformat = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') model = DB_Report fields = ('product', 'report_id', 'title', 'executive_summary', 'scope', 'outofscope', 'P_executive_summary', 'methodology', 'recommendation', 'report_date' ) widgets = { 'report_id': TextInput(attrs={'class': 'form-control', 'type': "text", 'required': "required"}), 'title': TextInput(attrs={'class': 'form-control', 'type': "text", 'required': "required"}), 'report_date': DateInput(attrs={'class': 'form-control', 'type': "text", 'data-inputmask': "'alias': 'yyyy-mm-dd'", 'data-mask':'', 'required': "required"}), 'P_executive_summary' : forms.BooleanField(), } models.py: exec_summary from DB_Product --> P_executive_summary in DB_Report class DB_Product(models.Model): name = models.CharField(max_length=255, blank=False) description = MartorField() … -
How to add an autocomplete field in an existing form?
Given a form class SettingsForm(Form): first_name = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'First name'}), label='', ) last_name = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Last name'}), label='', ) I'm trying to add an autocomplete field languages that suggests languages using the model below class Language(models.Model): name = models.CharField(max_length=255, unique=True) code = models.CharField(max_length=7, unique=True, null=True) def __str__(self): return self.name Based on django-autocomplete-light, I tried the below: languages = djhacker.formfield( Profile.languages, forms.ChoiceField, widget=autocomplete.ModelSelect2(url='language-autocomplete'), ) but it looks like formfield is not returning anything bootstrap5.exceptions.BootstrapError: Parameter "field" should contain a valid Django BoundField. [29/Dec/2022 13:58:56] "GET /settings/ HTTP/1.1" 500 182091 by checking further, the error above occurs because languages is None. If so, then how should I be adding languages as a field of the settings form? -
Django: Scheduled executeion of tasks
I'm building a Django system that needs to daily fetch data from another source (e.g. a daily dump of JSON files from a government site). The Django site is supposed to run in Docker, currently as a single server but optionally scaling later. I'd like to run the scheduled task internally inside Django (not using crontab or SystemD), but unsure how to do that. The schedule isn't dynamic (I'm happy setting the cadence in the Python code), and I don't want to have to run an external command aside from runserver. All of the solutions I found seem to necessitate running another component / command / process, and I wonder if there's a more elegant solution. -
How to write {% url ' ' %} for 2 and more multiple slugs?
im beginner in Django I try write url for go to next url if i use {% url tuman_url 'iib:mahalla' i.slug %} i get error: Reverse for 'mahalla' with arguments '(<Tuman: Sharof Rashidov Tumani>, 'ulugbek')' not found. 1 pattern(s) tried: ['(?P<tuman_slug>[-a-zA-Z0-9_]+)/mahalla/(?P<mahalla_slug>[-a-zA-Z0-9_]+)\Z'] my urls.py path('statistika/<slug:tuman_slug>/', show_one_stata, name='tuman_stata'), path('<slug:tuman_slug>/mahalla/<slug:mahalla_slug>', show_one_mahalla, name='mahalla'), my views.py def show_one_stata (request,tuman_slug:str): tuman_url = get_object_or_404(Tuman, slug=tuman_slug) tuman = Tuman.objects.all() citizen = Citizen.objects.all() category = Category.objects.all() mahalla = Mahalla.objects. context = { 'citizen' : citizen, 'category' : category, 'mahalla' : mahalla, 'tuman' : tuman, 'tuman_url' : tuman_url, return render(request, 'main/one_stata.html',context) def show_one_mahalla(request, mahalla_slug:str,tuman_slug:str) : citizen = Citizen.objects.all() nizo = Category.objects.all() mahalla_for = get_object_or_404(Mahalla, slug=mahalla_slug) tuman_url = get_object_or_404(Tuman, slug=mahalla_slug) context = { 'citizen':citizen, 'nizo':nizo, 'mahalla_for':mahalla_for, 'tuman_url':tuman_url, } return render(request, 'main/one_mahalla.html',context) my html {% for i in mahalla %} {% if i.tum == tuman_url %} <tr> <td style="font-weight: bold;"><a href="{% url tuman_url 'iib:mahalla' i.slug %}" style="text-decoration:none; color:black;">{{ i.name }}</a></td> <tr> {% endif %} {% endfor %} my models.py class Tuman(models.Model): name = models.CharField(max_length=100, db_index=True, verbose_name="Tuman") slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") def __str__(self): return self.name def get_absolute_url(self): return reverse('iib:tuman', kwargs={'tuman_slug': self.pk}) class Meta: verbose_name = 'Tumanlar' verbose_name_plural = 'Tumanlar' class Mahalla(models.Model): name = models.CharField(max_length=100, db_index=True, verbose_name="Mahallaning nomi") slug = models.SlugField(max_length=255, unique=True, … -
Websocket messages are lost with Django + websocket
I'm using Django to build a service which receives data from Binance crypto exchange in real time via websocket. I run several websocket connections, each of them in the separate thread. There is the function which starts all threads with websockets: def start_threads(self): query = self._socket_type.get_pairs_symbols(self.get_symbol_function(), provider=self._provider) for i in range(0, len(query), self._provider.limit_socket_pair_per_thread): socket = self._socket_type() thread = BaseThreadSocketWorker(socket, query[i: i + self._provider.limit_socket_pair_per_thread]) thread.start() Here I try to subscribe to all available pairs on Binance. I wasn't able to subscribe to all of them at once, websocket simple were stuck, that is why i split it to several connections. self._provider.limit_socket_pair_per_thread - number of pairs to subscribe in the websocket _socket_type.get_pairs_symbols - just formats and returns query which is accepted by Binance websocket. self._socket_type - my custom class to handle websocket messages and process received data BaseThreadSocketWorker - class inherited from threading.Thread python class. Overrides run method in which websocket is started. Here is a method implementation, where self._socket_handler is the same class as described for self._socket_type earlier. def run(self): self._socket_app = self._socket_handler.subscribe_to_prices_ws(self._observed_pairs) self._socket_app.run_forever() subscribe_to_prices_ws does the following. Creates a WebSocketApp instance, which subscribes to Binance weboscket (in my case it's wss://stream.binance.com:9443/ws), which suppose to send a messages any time prices … -
cannot acces http://server_domain_or_IP:8000
I am using an AzureVM to host my development API server written in django. There, I cloned my codebase and did all the requirements.txt installation. Before executing the manage.py runserver 0.0.0.0:8000 command, I changed the firewall permission rule: sudo ufw allow 8000. The sudo ufw status commads shows the following result: Status: active To Action From -- ------ ---- Nginx HTTP ALLOW Anywhere 8000 ALLOW Anywhere OpenSSH ALLOW Anywhere Nginx HTTP (v6) ALLOW Anywhere (v6) 8000 (v6) ALLOW Anywhere (v6) OpenSSH (v6) ALLOW Anywhere (v6) and then I run python3 manage.py runserver 0.0.0.0:8000. I should be able to see the default django page @ http://SERVER_IP_OR_DOMAIN:8000 But nothing shows. whereas if I hit http://SERVER_IP_OR_DOMAIN, I can see the NGINX landing page. I am following this blog from digital ocean. Here is my VM network rules: How can I fix this? -
How to filter with encrypted column in django?
Here I am encrypting some column in the db by making custom django model field. All were working fine but I am not able to filter with the encrypted column. from cryptography.fernet import Fernet from django.conf import settings from django.db import models class CustomTextField(models.TextField): key = settings.FERNET_KEY.encode() f = Fernet(key) def get_prep_value(self, value): return self.f.encrypt(value.encode()).decode() def from_db_value(self, value, expression, connection): return self.f.decrypt(value).decode() class MyModel(models.Model): text = CustomTextField(null=True) MyModel.objects.create(text="sometext") # saves text as 'gAAAAABjrZU-AiwR0EaQQ3lkYYd6GJnyNF0tNE1lYHmuUAKgydAA0nl2mYd4IuPoREatQSlwYMwWBYbvrYqPiryLwaL9OraeJA==' MyModel.objects.values("text") # returns "sometext" But the issue is while filtering For eg. MyModel.objects.filter(text="sometext") # return empty queryset -
PAGE NOT FOUND- ERROR(404);GET request; django-python
Lately I have been trying to use the GET request in django-python. However I run into a 404 error when I do so. I want the program to print the parameter given to it. URL PATTERN : path('add<int:hello>/',views.add,name = 'Add') VIEWS.PY: def add(request,num1): val1 = request.GET["num1"] return HttpResponse(request,"Hello") WHAT I AM SEARCHING ON BROWSER: http://127.0.0.1:8000/add?1 -
specific sending of a data to another user in django
I code a plateform project in django, a user can create an announce and a another user can reserv this announce.I would like that when User-A books on an announce of user-b, User-B receives the notification on the site, on a page notification, but I don't know how to do that. I tried something. My views.py : @login_required def view_annonce(request, annonce_id): message = "" annonce = get_object_or_404(models.Offre, id=annonce_id) if request.GET.get('contact') == 'contact': print('user clicked summary') if request.user.point_number < 10: message = "You can't reserv this announce" else : request.user.point_number = request.user.point_number -10 request.user.save() return redirect("home") context={ "annonce": annonce, } return render(request, 'blog/view_annonce.html', context=context) @login_required def notif_page(request): return render(request, 'blog/notifications.html') urls.py : path('offre/<int:annonce_id>', blog.views.view_annonce, name="view_offre"), path("offre/<int:annonce_id>/edit", blog.views.edit_annonce, name='edit_offre'), path("notif/", blog.views.notif_page, name="notif"), my models.py : class User(AbstractUser): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=30, null=True) profile_photo = models.ImageField(verbose_name='Photo de profile') point_number = models.IntegerField(default=20) ville = models.CharField(max_length=50) -
django query: groupby and keep rows that are the most recent
I am struggling on a query that is supposed to group by a model attribute and return for each unique value of that model attribute, the row that has the most recent date. I can't manage to get the output that I am looking for in a way that will be digestible for my template. here is the model I am trying to query: class Building(models.Model): building_id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True, blank=True) project = models.CharField(max_length=200,blank=True, null=True) and here are my attempt #1: get the unique projects and use a for loop: projects = list(Building.objects.all().values_list('project', flat=True).distinct()) context = {} for project in projects: proj = Building.objects.filter(project=project).latest("created_at") context[project] = proj this is ok but it does not allow me to access the queryset as {% for i in projects %} in template => causing pk problems for links my other attempt tries to get rows, to keep everything in a queryset: projects = Building.objects.all().values_list('project', flat=True).distinct() proj = Building.objects.filter(project__in=list(projects)).latest("created_at") that only returns the latest entered row regardless of the project name. This is close to what I am looking for, but not quite since I try to output the latest entered row for each unique project value. what is the proper way … -
Create the form with given requirements in Python
please Solve this. in python. file link :- https://drive.google.com/file/d/1Io5Ec-hZLIy3iA2vuS-WmEeoO3WiA8oU/view?usp=share_link Solve the full problem -
Is it possible to show message in DjangoAdmin on open?
I need to display a message right after I open model admin page, is there a way? I know how to show it after save, but didn't find a way to show it on open. -
How to restrict users from accessing product after it has expired?
I'm developing an e-learning app in which users can purchase courses that have an expiry date of up to two months from the time they purchase the course. I'm aware of how to limit their access by comparing dates, but I was hoping you could advise me on how to easily restrict the users without manually going through every view and calling a function that returns Permission Denied if their course has expired. I attempted to create a decorator that checks this but was unsuccessful. Should I use middleware to accomplish this? Could you point me in the right direction so I don't have to go through every view manually? -
Django api showing an import error upon running the server after using django-rest-auth
I was trying to build a Django API for a blog site. Up to this point, everything was working fine, but as soon as I tried to implement user authentication using Django-rest-auth and updated the urls.py files of both the app and the project accordingly, I have been getting this error that's apparently been telling me that the program can't locate 'URL' from Django.configs.urls. Here's the code of the urls.py file of the 'posts' app in the project:- from django.urls import path from .views import PostList,PostDetail urlpatterns = [ path('<int:pk>/',PostDetail.as_view()), path('',PostList.as_view()), ] Here's the code of the project level urls.py file:- from django.contrib import admin from django.urls import path,include #new urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/',include('posts.urls')), #new path('api-auth/', include('rest_framework.urls')), #new path('api/v1/rest-auth/',include('rest_auth.urls')), #new ] Here's the settings.py file of the project:- '''' 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/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-&u!b8$eururpem!f_0klrw2g28(xu14%i8h4g&k(i$@_tmmm$7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
How to write webhooks for telegram bot with aiogram and django
How do I write webhooks using aiogram and django. How do I send data to the bot received via webhooks ? Bot code from aiogram.utils.executor import start_webhook from aiogram.dispatcher.webhook import SendMessage from config import * @dp.message_handler() async def echo(message: types.Message): return SendMessage(message.chat.id, message.text) async def on_startup(dispatcher): await bot.set_webhook(WEBHOOK_URL, drop_pending_updates=True) async def on_shutdown(dispatcher): await bot.delete_webhook() if __name__ == '__main__': start_webhook( dispatcher=dp, webhook_path=WEBHOOK_PATH, skip_updates=True, on_startup=on_startup, on_shutdown=on_shutdown, host=WEBAPP_HOST, port=WEBAPP_PORT, ) Django code class Webhook(mixins.CreateModelMixin, viewsets.GenericViewSet): def get_message(self, request, *args, **kwargs): data = self.request.data # in this message for bot ... And how I can reply to bot this message ? -
django PostgreSQL Partitioning reference error
We have two models. I'm implementing partitioning on the PaymentModel. It gives an error when I want to add to the BuyerModel table linked to this table; insert or update on table "betik_app_payment_buyermodel" violates foreign key constraint "betik_app_payment_bu_payment_id_d7022880_fk_betik_app" DETAIL: Key (payment_id)=(2) is not present in table "betik_app_payment_paymentmodel". models.py @architect.install('partition', type='range', subtype='date', constraint='month', column='dt') class PaymentModel(models.Model): class Meta: app_label = 'betik_app_payment' indexes = [ models.Index(fields=['user_email']) ] payment_status = models.PositiveIntegerField(default=1) price = MoneyField(max_digits=20, decimal_places=2) dt = models.DateTimeField() user_email = models.EmailField(null=True, blank=True) token = models.CharField(max_length=255, null=True, blank=True) class BuyerModel(models.Model): class Meta: app_label = 'betik_app_payment' indexes = [ models.Index(fields=['name', 'surname']) ] payment = models.OneToOneField(to='betik_app_payment.PaymentModel', on_delete=models.CASCADE,related_name='buyer') name = models.CharField(max_length=100) surname = models.CharField(max_length=100) email = models.EmailField(null=True, blank=True) ip = models.GenericIPAddressField(null=True, blank=True) main.py from datetime import datetime from djmoney.money import Money buyer_name="Name" buyer_surname="Surname" buyer_email="developer@betik.com.tr" buyer_ip="10.0.0.1" price= Money("100.00","TRY") payment_instance = PaymentModel.objects.create( price=price, dt=datetime.now(), user_email=buyer_email ) # raise error at here buyer_instance = BuyerModel.objects.create( payment=payment_instance, name=buyer_name, surname=buyer_surname, email=buyer_email, ip=buyer_ip ) using library: money partition I'm looking at the tables in the database with the pgadmin tool and the partition has been applied successfully. data added in both tables. But BuyerModel table is empty PaymentModel table has two triggers. These triggers are created automatically by the architect library. Maybe there … -
How to allow only custom urls in Django rest api?
I'm trying to create a simple api to learn how Django works. I'm using rest_framework. First, I have created a model: class User(models.Model): username = models.CharField(max_length=20, primary_key=True) password = models.CharField(max_length=50) token = models.UUIDField(default=uuid.uuid4, editable=False) creation_dt = models.DateTimeField(auto_now_add=True) Then I have created a serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'token', 'creation_dt') read_only_fields = ('creation_dt', 'token',) And then, in api.py, this code: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() permission_classes = [permissions.AllowAny] serializer_class = UserSerializer http_method_names = ['get', 'post'] @action(methods=['POST'], detail=False, permission_classes=[permissions.AllowAny], url_path='get_all_users') def get_all_users(self, request, pk=None): ... return Response(UserSerializer(self.queryset[:user_number], As you can see, I added a custom url_path "get_all_users". So, everything works until here. My problem is that I can still access "/users/", "/users/user_name", POST users etc, the normal CRUD app. The question is, how can I allow only the url I have especifially created and block all the rest created automatically? Thanks. -
django_filters - Filters are not responsive (function based view)
Trying to implement a filter django_filters to an existing function based view. The filter is rendering as it should, but nothing is happening. There is a few question on the topic, so I am going to answer some potential questions: I used $ pip install django-filter I installed in my virtual environment Filter.py is installed in the same app as the views Something to mention in my filters.py, import django_filters is underlined in red ("Import "django_filters" could not be resolved"). I cant find why, but this could be a strong contender in the root cause of the problem. Settings file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "crispy_forms", 'main.apps.MainConfig', 'django_filters', models class Catalogue(models.Model): product = models.ManyToManyField('Product', blank=True) product_title = models.TextField('Product Title', blank=True) class Meta: db_table='Catalogue' def __str__(self): return str(self.product_title) filters import django_filters from .models import * class CatalogueFilter(django_filters.FilterSet): class Meta: model = Catalogue fields = ['product_title'] views from .filters import CatalogueFilter def show_venue(request, venue_id): if request.method == "POST" and 'btnreview_form' in request.POST: form = CatalogueReviewForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.product_id = venue_id # links to product ID in Catalogue Model and return product name data.venue_id = request.POST.get('venue_id') # prints venue ID in form data.user_id = request.user.id data.save() … -
Django Migrations: How to mark a migration as a parent of other apps migrations?
I'm trying to create a new Django application whose migrations depends on other apps migrations. I want migrations on the other apps to have a dependency on migrations on the new application, even when the new application doesn't reference at all the models at the other apps. For example, let's say I have application A (an existing app) and application B (my new application): A has a migration called A.0001, and B has a migration called B.0001 which depends on A.0001. I now make a change at A.MyModel, so I need to run python manage.py makemigrations to generate a new migration A.0002. What I want is A.0002 to automatically depend on B.0001. How can I specify this dependency on new migrations in A without having to do it by hand each time I modify a model in A? I tried to add empty modifications of models in A at the migration B.0001, but I haven't got it to work and it looks very hacky to me. -
How to handle Invalid base64-encoded string error with fernet decrypt?
class MyModel(models.Model): value = models.CharField(max_length=255) I am trying to encrypt this field in the db. def encrypt_value(val): key = settings.ENCRYPT_KEY.encode() f = Fernet(key) return f.encrypt(val.encode()) MyModel.objects.create(value=encrypt_value(val)) # saves into the db like this `\x674141414141426a72584c714e355574383343337937636a41666e4d714f357034535464394e5f6b395461524975692d7346696f586b34586d78694a5a485f314c6e696854776e6d7548645a5451765f7a66324139446a334c724c7475694b424b524753454b4c4b5f34705a50535246784a56416b70383d` decypt value model = MyModel.objects.get(id=1) value = decrypt_value(model.val) def decrypt_value(val): key = settings.ENCRYPT_KEY.encode() f = Fernet(key) return f.decrypt(val).decode() But with decrypt getting InvalidToken: error -
How to fix UNIQUE constraint failed: users_profile.user_id?
How to fix UNIQUE constraint failed: users_profile.user_id? already have a created profile views.py class EditProfile(CreateView): model = Profile context_object_name = 'profile' template_name = 'users/profile_edit.html' fields = ['avatar', 'name', 'description'] success_url = reverse_lazy('users:profile') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) urls.py path('<slug:slug>/edit/', EditProfile.as_view(), name='profile_edit'), models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='users/avatars/%Y/%m/%d/', blank=True) name = models.CharField(max_length=20, blank=True) description = models.CharField(max_length=250, blank=True) slug = models.SlugField(max_length=50, blank=True) def __str__(self): return f"{self.user}" def save(self, *args, **kwargs): self.slug = slugify(self.user) super(Profile, self).save(*args, **kwargs) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver def save_profile(sender, instance, **kwargs): instance.profile.save() -
Not able to find template in Django Framework
As part of a project, I'm developing a social networking website. When I try to load a webpage, a django.template.exceptions error message appears. TemplateDoesNotExist. I have examined every setting, installed application, and template directory item in relation to their position. Everything was running smoothly without any issues up until yesterday. When I began working today, I started running across this issue. The location in the errors is exactly right, thus I don't understand how it can't locate the template. Additionally, I have four templates, of which two (the recently built ones) are experiencing this issue while the other two load without any issues.[Images of Error I am facing right now](enter image description here) I am trying to display a HTML file and expecting to come over on my browser.