Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Declarative mechanism for Django model rows
With some frequency, I end up with models who contents are approximately constant. For example, I might have a set of plans that users can sign up for, with various attributes -- ID, name, order in the list of plans, cost, whether the purchaser needs to be a student/FOSS project/etc.. I'm going to rarely add/remove/change rows, and when I do there's likely going to be code changes too (eg, to change landing pages), so I'd like the contents of the model (not just the schema) to be managed in the code rather than through the Django admin (and consequently use pull requests to manage them, make sure test deploys are in sync, etc.). I'd also like it to be in the database, though, so I can select them using any column of the model, filter for things like "show me any project owned by a paid account", etc.. What are good ways of handling this? I think my ideal would be something like "have a list of model instances in my code, and either Django's ORM magically pretends they're actually in the database, or makemigrations makes data migrations for me", but I don't think that exists? The two workable approaches … -
Printing kwargs.pop displays the right value, using it in a method takes None
I ant to pass a PK in kwargs to a form : views.py def create_mapping_form(request, pk): context = { 'form': MappingForm(pk=pk) } return render(request, 'flows/partials/mapping_form.html', context) In the form i retrieve the PK using : forms.py class MappingForm(forms.ModelForm): class Meta: model = MappingField fields = ( 'fl_col_number', 'fl_col_header', 'fl_cross_field_name', 'fl_cross_position', 'fl_replace_list' ) def __init__(self, *args, **kwargs): pk = kwargs.pop('pk', 'Rien') super(MappingForm, self).__init__(*args, **kwargs) #print(pk) self.helper = FormHelper(self) self.fields['fl_replace_list'].widget.attrs[ 'placeholder'] = "Liste de tuples eg. : [('reman','ES'), ('Gasoline','Diesel')] " headers = GetCsvHeadersAndSamples(pk)['headers'] [...] For populating some fields' CHOICES, I use a method that returns a dic (last line above) headers = GetCsvHeadersAndSamples(pk)['headers'] But something I can't explain sends 'Rien' to GetCsvHeadersAndSamples while when I print(pk) the right value is shown. (GetCsvHeadersAndSamples is not useful, I don't show it) Nota: I display the form in template using HTMX. The issue seems not coming from HTMX because when I hard-code the PK, everything is ok. For the time, I have found nothing else but stocking the PK value in a "temp" file but this slows my script. Thanks -
How to make a model's entries as a field.options list in other model's field?
I have two models - Account, like checking, wallet, credit, etc. and Transaction which includes each purchase and earning. Transaction has a foreign key to Account. In Transaction, I want users to select the Account of purchase. I considered the field.choices but the choices are permanent. I want users to select a choice of Account from Account models. How do I do that? -
bootstrap cdn not working in a django website
this is how it looks with online CDN.how I want it to look and when I give it the offline CDN path this is how it looks -
Avoid csrf token in django post method
I am making part of the web app where (unlogged users, all visitors) can fill the form and I have to save that data (name, phone number, question) in database.. I am making REST using Django, but for frontend I will use React or Django, and I am making POST method in Django framework that reads JSON data from POST https request, and then I save that data to database.. But I get error CSRF verification failed. Request aborted. because I don not use CSRF token, because it is not required for this (I do not have logged users). But I do not want to disable CSRF, because for admin page I would use this to authenticate users? So anyone knows how to avoid using CSRF token for this method? Thanks in advance.. def saveDataToDatabase(request): if request.method == 'POST': json_data = json.loads(request.body) try: data = json_data['data'] except KeyError: HttpResponseServerError("Malformed data!") This is the part of method.. -
'Stocks' object is not iterable - Django
I saw that there are other people who have my problem, but I still can't solve the problem ... thanks to anyone who will help me! models.py class Stocks(models.Model): image = models.ImageField() name = models.CharField(max_length=50) value = models.FloatField() desc = models.CharField(max_length=299) link = models.CharField(max_length=30) views.py def stocks_mt(request): return render(request, 'azmt.html', {'stock': Stocks},) home.html <div class="container"> <div class="row"> {% for Stocks in stock %} <div class="col-sm"> <br><div class="card" style="width: 18rem;"> <img src="{{stocks.image}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title text-center">{stocks.name}</h5> <!--<h5 class="card-text text-center">50.90€</h5>--> <p class="card-text ">{{stocks.desc}}</p> <h5 class="card-text text-center">{{stocks.value}}</h5> <a href="{{stocks.link}}" class="btn btn-primary">Buy</a> </div> </div> </div> {% endfor %} </div> I tried to capitalize the first letter but nothing has changed ... -
'GenericRelatedObjectManager' object has no attribute 'lang'
I am receiving the error 'GenericRelatedObjectManager' object has no attribute 'lang' when I making a post request. In this query and relationship I have two models Translation and Tags. class Translation(models.Model): """ Model that stores all translations """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.CharField(max_length=50, null=True, blank=True) content_object = GenericForeignKey() lang = models.CharField(max_length=5) field = models.CharField(max_length=255, null=True) translation = models.TextField(blank=True, null=True) def __unicode__(self): return u'%s : %s : %s' % (self.content_object, self.lang, self.field) class Tags(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) DISEASE = 0 TYPE = [(DISEASE, 'disease')] type = models.PositiveSmallIntegerField(choices=TYPE) name = GenericRelation(Translation) description = GenericRelation(Translation) I am creating a serializer mixin to send the same data to different serializer (not only the Tag described below): SerializerTranslationField and TagSerialzer: class SerializerTranslationField(Field): def __init__(self, method_name=None, model_name=None, translation_field=None, **kwargs): self.method_name = method_name self.translation_field = translation_field self.model_name = model_name kwargs['source'] = '*' kwargs['read_only'] = True print("KWARGS ----->", kwargs) super().__init__(**kwargs) def to_representation(self, value): content_type = ContentType.objects.get_for_model(self.model_name) queryset = Translation.objects.filter(content_type=content_type, object_id=value, field=self.translation_field) result = TranslationSerializer(queryset, required=False, many=True).data final_result = {k: v for d in result for k, v in d.items()} print("FINAL RESULT --->", final_result) return final_result class TagsSerializer(NestedUpdateMixin,serializers.ModelSerializer): class Meta: model = Tags fields = ['id', 'type', 'name','description'] def __init__(self, *args, **kwargs): fields … -
How show image in django pdfkit pdf file?
I have a issue, I create detail view in html and after i convert it in pdf for all models object. i use pdfkit, however it doesnt shows object's image, then i run code with image it has some errors. def customer_render_pdf_view(request, pk): posts = get_object_or_404(Person, pk=pk) enrolment =get_object_or_404(Enrollment, pk=pk) template = get_template('test.html') html = template.render({'costumer': posts, 'enrolment':enrolment}) options = { 'page-size': 'Letter', 'encoding':' base64.b64encode("utf-8")', } pdf = pdfkit.from_string(html, False, options) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="person.pdf"' return response my HTML code : <img src={{costumer.image.url}} height='200px'> -
django retrieve all items filtering by FK
I would like to make an API for retrieve all the dailies of a specific tracker for then retrieve them in react native, could you give me some help about how do it? thanks in advance. I also have User and Habit classes, but in this case i just need this API. class Tracker(models.Model): habit = models.ForeignKey(Habit, on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='trackers', on_delete=models.CASCADE) start_date = models.DateField(blank=False) end_date = models.DateField(blank=False) published = models.BooleanField(blank=False) @property def habit_title(self): return self.habit.title def is_active(self): today = datetime.now().date() return (today >= self.start_date) and (today <= self.end_date) def no_of_days(self): return abs((self.end_date-self.start_date).days) + 1 class Daily(models.Model): STATUS = [('DONE', 'DONE'), ('TODO', 'TODO'), ('NOTDONE', 'NOTDONE'),] date = models.DateField() status = models.CharField(choices=STATUS, max_length=10, default='TODO') tracker = models.ForeignKey(Tracker, on_delete=models.CASCADE) class Meta: unique_together = (('date', 'tracker'),) index_together = (('date', 'tracker'),) serizalizers.py class TrackerSerializer(serializers.ModelSerializer): habit_title = serializers.ReadOnlyField() class Meta: model = Tracker fields = ['id', 'start_date', 'end_date', 'published', 'is_active', 'no_of_days', 'habit', 'habit_title', 'user'] def create(self, validated_data): tracker = Tracker.objects.create(**validated_data) diff = abs((validated_data['start_date'] - validated_data['end_date']).days) for i in range(0, diff + 1): Daily.objects.create(date=(validated_data['start_date'] + timedelta(days=i)), tracker=tracker) return tracker class DailySerializer(serializers.ModelSerializer): class Meta: model = Daily fields = ['id', 'date', 'status', 'tracker'] views.py class TrackerViewSet(viewsets.ModelViewSet): serializer_class = TrackerSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def … -
Running pytest using django manage.py, clear cache option
There are several tests, written with pytest, in my django app I run test using manage.py test with setting TEST_RUNNER = 'PytestTestRunner' PytestTestRunner class class PytestTestRunner: def __init__(self, verbosity=1, failfast=False, keepdb=False, **kwargs): self.verbosity = verbosity self.failfast = failfast self.keepdb = keepdb @classmethod def add_arguments(cls, parser): parser.add_argument( '--keepdb', action='store_true', help='Preserves the test DB between runs.' ) def run_tests(self, test_labels): import pytest argv = [] if self.verbosity == 0: argv.append('--quiet') if self.verbosity == 2: argv.append('--verbose') if self.verbosity == 3: argv.append('-vv') if self.failfast: argv.append('--exitfirst') if self.keepdb: argv.append('--reuse-db') argv.append('--cache-clear') argv.extend(test_labels) return pytest.main(argv) The problem is, that even i have option --cache-clear, the .pytest_cache directory is still created How to prevent this behaviour? -
submit html form django
i have this django app and i'm trying to submit form but study material file field have multiple file select option so what i'm trying to do create keylevel with name description status after that with keylevel id i'm saving files in another table. models.py: class KeyLevel(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(null=True, blank=True) status = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class KeylevelFileUpload(models.Model): key_level_id = models.ForeignKey(KeyLevel, related_name="keylevel", to_field="id", verbose_name=_("Key Level Id"),on_delete=models.CASCADE, null=True, blank=True, db_column="key_level_id") study_material = models.FileField(upload_to='study_material', null=True, blank=True) status = models.SmallIntegerField(verbose_name=_("Status: 1 for Active; 0:Inactive"), default=1) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) html: <form method="post" action="{% url 'keyLevelAdd'%}" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-md-3"> <div class="formControl static"> <label for="levelName" class="formLabel">{{form.name.label}}</label> <input type="text" name="{{form.name.html_name}}" class="formField" placeholder="Scripture Key Level" id="levelName"> </div> </div> <div class="col-md-4"> <div class="formControl static"> <label for="" class="formLabel">Study Material</label> <div class="upload-input"> <input type="file" name="{{form.study_material.html_name}}" class="formField" placeholder="Scripture Key Level" id="studyMaterial" multiple> </div> <div class="upload-icon"> <div class="browseImg"> <i class="fas fa-upload"></i> {% comment %} <input type="file" class="browseField" name="studyMaterialbrowse" id="studyMaterialb" multiple> {% endcomment %} </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="formControl static textarea"> <label for="" class="formLabel">{{form.description.label}}</label> <!-- <label for="" class="formLabel">About Level Conditions</label> --> <textarea class="formField" placeholder="" rows="5" name="{{form.description.html_name}}">Description</textarea> </div> </div> <div class="col-md-3"> <div … -
For loop not working as expected in Django, HTML
I'm trying to create a search bar where the user can search for a specific user in the database. I've created a for loop in the search_users HTML file but the loop is not iterating through any of my users. Whenever I try to load the page the first line loads ("You searched for ...") but anything in the for loop does not. models.py class User(AbstractUser): """User in a club.""" username = models.EmailField(unique=True, blank=False) first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) bio = models.CharField(max_length=520, blank=True) chess_experience = models.IntegerField(blank=False, validators = [MinValueValidator(0)]) personal_statement = models.CharField(max_length=10000, blank=False) created_at = models.DateTimeField(auto_now_add=True) views.py def search_users(request): if request.method == "POST": searched = request.POST.get('searched',False) users = User.objects.filter(first_name__contains=searched) return render(request, 'search_users.html', {'searched': searched, 'users': users}) else: return render(request, 'search_users.html', {}) search_users.html {% if searched %} <h1>You searched for {{ searched }}</h1> {% for user in users %} <a href="{% url 'show_user' user.id %}">{{ user }}</a><br/> {% endfor %} {% else %} <h1>You forgot to search for a member...</h1> {% endif %} -
Angular to Django. File Uploader with a Date Parameter
I have some working code on Django, where i created a simple file uploader with a date picker that is passed through a view and then uploaded onto a database using a standalone python class that utilise sqlalchemy. However, I have been working on migrating the UI aspect onto an Angular Front End, but hit a road block and not sure where I am going wrong. The user needs to be able upload a excel binary file, input a date and hit upload. This should send a request to a view which then handles the request. The view it self works perfectly, when the file and dates are inputted from the Django HTML template. But I can't seem to make it work once the inputs come from Angular. Here is my code views.py @api_view(('POST',)) @csrf_exempt def uploader(request): if request.method == 'POST': try: instance= uploader(request.FILES['data'], request.POST['selectedDate']) _ = upload_instance.run_upload_process('data') upload_message = "Success" return Response(upload_message, status=status.HTTP_201_CREATED) except Exception as e: upload_message = 'Error: ' + str(e) return Response(upload_message, status=status.HTTP_400_BAD_REQUEST) file-upload.service.ts DJANGO_SERVER: string = "http://127.0.0.1:8000"; constructor(private http:HttpClient) { } public upload(data: any, selectedDate:any) { return this.http.post<any>(`${this.DJANGO_SERVER}/upload/`, data, selectedDate); } upload.component.ts onChange(event: any) { this.filetoUpload = event.target.files[0]; } inputEvent(event:any) { this.monthEndDate = event.value; } … -
Can not raise ValidationError in django update serializer
I'm trying to raise ValidationError in an update serializer, but couldn't. Here is my code: from rest_framework.exceptions import ValidationError class PersonUpdateSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ( "name", "surname", ) def validate(self, attrs): # type: (dict) -> dict errors = {} attrs = super(PersonUpdateSerializer, self).validate( attrs ) if "surname" not in attrs: errors["surname"] = "This field is required." if errors: raise ValidationError(errors) return attrs def update(self, instance, validated_data): for key in validated_data: setattr(instance, key, validated_data.get(key)) instance.clean() instance.save() return instance When I don't send "surname" parameter, it should raise ValidationError, but it doesn't. What am I missing? -
How to get user id from the related field model in django?
views.py @login_required def become_vendor(request): vendordetailform = VendorAdminDetailsForm() if request.method == 'POST': vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendordetailform.is_valid(): vendordetailform.instance.vendoruser = request.user request.user=vendordetailform.save() request.user.is_active=False request.user.save() user_details = CustomUser.objects.filter(id=request.user) vendor_details = user_details[0].vendor_details.all() return render(request,'vendor/preview.html', {'user_details':user_details, 'vendor_details':vendor_details}) else: vendordetailform = VendorAdminDetailsForm() return render(request, 'vendor/become_vendor.html', {'vendordetailform':vendordetailform}) I have two models 1. User model, 2. VendorDetails model (vendoruser is connected by foreignkey relationship with vendordetails) Here I save the User extra details (VendorDetailsForm) if the requested user is applying for a vendor. I could be saved the requested user details in VendorDetails Model. But when I am getting the requested user id, I can't . instead I get vendordetails model foreignkey field. Here I want to inactive the requested user who came with this vendor details form. I am getting Field 'id' expected a number but got <VendorDetails: yabeshofz@gmail.com-Customer1>. -
Django ModelForm how to display only a subset of Model
I have a django model for an appointment to the doctor class Appointment(models.Model): patient=models.ForeignKey(Patient,on_delete=models.SET_NULL,null=True) date=models.DateField(default=datetime.date.today) doctor=models.ForeignKey(Profile,on_delete=CASCADE) status=models.CharField(max_length=12,default="open") def __str__(self): return self.name Doctor is one of the roles in the Profile model. My form is defined like so class AppointmentForm(forms.ModelForm): class Meta: model=Appointment exclude = ['id'] def __init__(self,*args,**kwargs): super().__init__(*args, **kwargs) self.helper=FormHelper() self.helper.layout=Layout( Row( Column('patient',css_class="form-control, col-md-4 mb-0"), Column('date',css_class="form-group, col-md-4 mb-0"), Column('doctor',css_class="form-group, col-md-4 mb-0"), css_class='row ' ), Submit('btn_save', 'Save',css_class='btn-success') ) When displaying the form using crispy forms, all the users of the Profile models are shown. How do I display only Profiles with role Doctor? -
Bind cache Django class based view response with parameter from request
I want to cache my API response and bind it with parameter that is present in GET request. The request looks like this: GET /products?producent=some_company Here is my simplified class: class ProductsListCreate(generics.ListCreateAPIView): def list(self, request, *args, **kwargs): cached_response = cache.get(f"response-products-{producent}", None) if not cached_products: queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) serializer = self.get_serializer(page) response = self.get_paginated_response(serializer.data) producent = request.query_params.get("producent") cache.set(f"response-products-{producent}", products, timeout=20) return response return cached_response But when I'm trying to cache the response I receive error: django.template.response.ContentNotRenderedError: The response content must be rendered before it can be pickled. Do you have any tips for me? I was searching here https://docs.djangoproject.com/en/3.2/topics/cache/ when I was trying to figure out this. At first I tried the approach with @cache_page but it won't allow me to use the parameter from request, so I guess the way to go is Low level cache API. -
Difference pip/pipenv
I guess it's going to be obvious in a few seconds but I am fairly new to web development. I am learning how to use Django and I encountered an issue with allauth after having installed it through pipenv and tried to migrate. I got a lovely ModuleNotFoundError: No module named 'allauth'. As I said, I installed it through pipenv and I could see allauth in my .venv/Lib/site-packages file. I have my virtual environment set and activated. A quick research and thanks to this answer, I solved my issue by "reinstalling" it with pip install allauth, and my migration is now working fine. What I don't understand is, wasn't it already installed when I did pipenv install allauth, do I need to install everything once with pipenv to get the Pipfile & Pipfile.lock updated and then also install it through pip...? Obviously, I don't fully understand the difference between pipenv & pip, if some charitable soul would be kind enough to explain this to me, I'd greatly appreciate it :) Edit: I saw this thread already but either way I am stupid or whatever but it still doesn't make much sense to me. -
Passing JSON from custom view to template
So I have worked with a Django program that was working before, got some code got lost and I managed to recover the most, but have some issues left. I have a class that's building different dictionaries that are supposed to be passed on to the frontend, where there are some Javascript function that's work with that data. My problem is I can't get the pass the data from the view to the template. I have tried to use HttpResponse, but then it just displays the data on a blank screen. I just want to pass it to the template and let the JavaScript functions there work with it. class ReportDashboardView(AuthMixinLineManager, ReportDashboard, generic.TemplateView): """Team report view, build data required for graphs and tables.""" template_name = 'index.html' http_method_names = ['get'] def get(self, request): data_left, data_joined, data_changed_team = self.init_report() data_left = json.dumps(data_left) return HttpResponse(json.dumps(data_left), content_type="application/json") Looks like this I instead just want to "feed" the data to the already existing HTML-template and use the escapejs to access the data that comes from the view. I know the URL-patterns is correct. And here is a example of how the JavaScript functions looks. So my questions is, does anyone have any suggestion on how … -
How to filter many2many field with another many2many?
I have following model in my Django: class Filter(models.Model): min_price = models.PositiveIntegerField(null=False, blank=False) max_price = models.PositiveIntegerField(null=False, blank=False) trait = models.ManyToManyField(Trait, null=True, blank=True) class Flat(models.Model): living_area = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, db_index=True) trait = models.ManyToManyField(Trait) class Trait(models.Model): name = models.CharField(max_length=255, blank=False, null=False, db_index=True) In my case trait can be for example: elevator. If there is connection between Flat and Trait(name="Elevator") then I can assume that Flat has elevator. What I want to do is to searching flats based on traits - traits from Flat and traits from Filter should be the same. I did somethink like this: filte_obj = Filter.objects.get(pk=pk) flat = Flat.objects.filter(trait__id__in=[x.id for x in filter_obj.trait.all()]) Unfortunately I does not work as I want. I want to see only Flats which Traits QuerySet is the same as Filter's traits QuerySet. How can I do that? -
How can I filter out static logs on Heroku Papertrail for a Django App?
I am trying to filter out logs related to static files on a Heroku/Django App. Based on this answer django - how to filter out GET static and media messages with logging? I added the following code snippet in settings.py def skip_static_requests(record): if record.args[0].startswith('GET /static/'): # filter whatever you want return False return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { # use Django's built in CallbackFilter to point to your filter 'skip_static_requests': { '()': 'django.utils.log.CallbackFilter', 'callback': skip_static_requests } }, 'formatters': { # django's default formatter 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[%(server_time)s] %(message)s', } }, 'handlers': { # django's default handler... 'django.server': { 'level': 'INFO', 'filters': ['skip_static_requests'], # <- ...with one change 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, }, 'loggers': { # django's default logger 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False, }, } } I was able to filter out static logs, but it only works on localhost. How can I get this to work for Heroku Logs and for a logging service like papertrail? -
Django+Twilio: How can I display inside my django app the sms I sent/received using twilio? (Architecture question)
I have a high level architecture question: I built a django app and I integrated with Twilio so that I can send SMS from my django app. Now I am trying to understand if there is a way for me to display the sms I send and receive almost as a chat inside my application. I know this is very high level but I am mostly looking for architecture suggestions, not specific code. Any suggestion? -
How to get field : Django RestFramework
How to get duration field from the table video, In my project there are two tables related to video models.py class Video(BaseModel, Timestamps, SoftDelete): video_name = models.CharField(max_length=254, null=True, blank=True) description = models.TextField(null=True, blank=True) duration = models.DurationField(null=True, blank=True) class VideoDetails(BaseModel, Timestamps, SoftDelete): max_attempt_allowed = models.PositiveSmallIntegerField() amount = models.DecimalField(max_digits=19, decimal_places=2) video = models.OneToOneField(Video, on_delete=models.CASCADE) Here I want to calculate total duration of a course, for that created a function: def get_duration(course_id): print('course', course_id) hour = VideoDetails.objects.filter(video__coursemodulevideos__module_id__coursesectionmodule__section_id__coursesectiondetails__course=course_id).aggregate(Sum('duration')) print('h', hour) "hour = VideoDetails.objects.filter(video__coursemodulevideos__module_id__coursesectionmodule__section_id__coursesectiondetails__course=course_id).aggregate(Sum('duration'))" through the above line how to get duration from video model, give me a solution to fix this situation -
Why is Django giving me a ValueError when I reference a class within the same model?
I'm building a simple recipe app, and so far I have two models: Ingredient and Recipe. Each recipe should have multiple ingredients, so I laid out my model like this: class Ingredient(models.Model): name = models.CharField(max_length=50) class Recipe(models.Model): title = models.CharField(max_length=100) ingredients = models.ForeignKey(Ingredient, on_delete=CASCADE) instructions = JSONField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=SET_DEFAULT, default='Chef Anon') When I makemigrations, I get nothing, but when I migrate, I get this ValueError: ValueError: Cannot alter field cookbook.Recipe.ingredients into cookbook.Recipe.ingredients - they do not properly define db_type (are you using a badly-written custom field?) Following the example here (Django: Add foreign key in same model but different class), I've tried setting ingredients=models.ForeignKey(Ingredient, on_delete=CASCADE) as well as using lazy syntax ingredients=models.ForeignKey("Ingredient", on_delete=CASCADE), but each time, makemigrations shows no changes, and migrate gives me the same ValueError. -
Django Multilanguage - allow users to translate their own input
I'm writing a multilanguage application for renting out property. I've succesfully translated all of the static content inside my application, but the input that the user gives is dynamic and needs to be translated by them. Example: The user needs to create all the different rental types that are available for a client to choose from. However, for each language this type has a different name because it needs to be translated. Ideally, when creating a rental type, the user should see multiple input fields for the name: one for each language. Django should then determine by the client's language which name to show. I've tried using django-modeltranslation and that created some extra columns on my database, but I cannot find a way for a user to edit all of these columns from one view. This is my translation.py # translation.py from modeltranslation.translator import register, TranslationOptions from .models import RentalType, Costs @register(RentalType) class RentalTypeTranslationOptions(TranslationOptions): fields = ('type', 'slug') @register(Costs) class CostTranslationOptions(TranslationOptions): fields = ('name',) Which were succesfully migrated to my database: Migrations for 'main': main\migrations\0014_auto_20211202_1559.py - Add field name_en to costs - Add field name_fr to costs - Add field name_nl to costs - Add field slug_en to rentaltype - …