Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UnicodeDecodeError: 'utf-8' codec can't decode, when uploading from testscript
I am making test script to upload excel file, def test_upload(self): c = Client() with open('_material/trick.xlsx') as fp: c.post('/cms/template/up', {'name': 'fred','content_file': fp}) There comes the error UnicodeDecodeError: 'utf-8' codec can't decode byte 0x85 in position 16: invalid start byte However in html upload form, there is no error occurs. class UploadTemplateFileForm(BaseModelForm): content_file = forms.FileField(required=True) Why this difference occurs? -
DJango rest framework - API list using filter field from related models
Hi I'm new to Django and the Django rest framework so my terminology may be off. I'm trying to build an API that gives back a list of items from a model but filtered based on fields in another related model. I'll provide my current view and serializer classes and models class service(models.Model): name = models.CharField(max_length=50) vendor = models.CharField(max_length=50) version = models.CharField(max_length=10) registration_status = models.BooleanField(default=False) class service_network(models.Model): service = models.OneToOneField( service, related_name='network', on_delete=models.CASCADE, primary_key=True, ) forwarded_port = models.CharField(max_length=50) class ServiceNetworkSerializer(serializers.ModelSerializer): class Meta: model = service_network fields = '__all__' class ServiceSerializer(serializers.ModelSerializer): network = ServiceNetworkSerializer() class Meta: model = service fields = [ 'id', 'name', 'vendor', 'version', 'registration_status', 'network', ] class ServiceAPI(ModelViewSet): queryset = service.objects.all() serializer_class = ServiceSerializer filterset_fields = '__all__' Currently I can get back lists using a URL query string {{baseUrl}}/engine/service?registration_status=true What I want to do is something like this {{baseUrl}}/engine/service/network?farwarded_port=8080 Which I would expect to give back a list of services where the related network field "forwarded_port" is equal to 8080. Is there another way to query this API? Maybe using a POST with a body containing the query? If there something in the DOCS that I can read, I've tried to look through filtering and querysets but I … -
How to write unit test for deleting a model instance in django admin
I have to override def get_deleted_objects(self, objs, request): function in order to abort the deletion process in Django admin, now I want to write a unit test for the same. def get_deleted_objects(self, objs, request): if condition: self.message_user(request, "You cannot delete this instance", messages.ERROR) return [], {}, {MyModel._meta.verbose_name.title()}, [] return super().get_deleted_objects(objs, request) -
how to fetch parent table field value using queryset object in django template
I have below models - Parent table - class RoomCategory(models.Model): trust = models.ForeignKey(Trust, on_delete=models.CASCADE, blank=True, null=True) *category = models.CharField(max_length=50,db_index=True)* rate = models.FloatField() description = models.CharField(max_length=500, blank=True, null=True) num_guests = models.IntegerField(blank=True, null=True) num_bedrooms = models.IntegerField(blank=True, null=True) num_beds = models.IntegerField(blank=True, null=True) num_toilets = models.IntegerField(blank=True, null=True) child table1 having above room category pics as below class RoomCategoryAttribute(models.Model): trust = models.ForeignKey(Trust, on_delete=models.CASCADE, blank=True, null=True) category = models.ForeignKey(RoomCategory, on_delete=models.CASCADE, blank=True, null=True) *image=models.ImageField(upload_to="room_cat_imgs/",null=True)* child table2 having booking details class Booking(models.Model): trust = models.ForeignKey(Trust, on_delete=models.CASCADE, db_index=True,blank=True, null=True) *category = models.ForeignKey(RoomCategory, on_delete=models.CASCADE, blank=True, null=True)* user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) check_in = models.DateTimeField(db_index=True) check_out = models.DateTimeField(db_index=True) phone_no = models.IntegerField(blank=True, null=True, db_index=True) num_days = models.IntegerField(blank=True, null=True) total_cost = models.IntegerField(blank=True, null=True) when_booked = models.DateTimeField(blank=True, null=True, db_index=True) I have a below queryset in my views.py - booking = Booking.objects.all() In my template I am iterating over the above booking query set to show the bookings in cards as below {% for booking in booking_list %} Now the question is - in the cards - how do I show the first image from the child table1 i.e. RoomCategoryAttribute which has multiple rows of several images per RoomCategory - as I think there is some way to use ***_set.first.image and I … -
Ajax success function does not triggered
i have a comment system in django. I am trying to make post request with ajax, information in the form stored in database, but ajax success function doesn't work. So, this is my ajax post method $('#parentComment').submit(function(e){ e.preventDefault(); const url = $(this).attr('action'); const btn = $('.comment-btn').attr('name'); const body = $('#parentCommentText').val(); $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'btn': btn, 'body': body, }, sucess: function(response){ console.log(response) }, error: function(response){ alert('error'); } }); }) So this is views.py file class Articlepage(View): def get(self, request, pk, *args, **kwargs): article = Articles.objects.get(id=pk) comments = article.messages_set.all() likes_count = article.likes.count() context = {'article': article, 'comments': comments, 'likes': likes_count} return render(request, 'base/main_article.html', context) def post(self, request, pk, *args, **kwargs): article = Articles.objects.get(id=pk) comments = article.messages_set.all() likes_count = article.likes.count() if 'parent-comment-submit' in request.POST['btn']: try: value = request.POST.get('parent') parent = Messages.objects.get(id=int(value)) except: parent = None body = request.POST.get('body') if body: comment = Messages.objects.create( user = request.user, article = article, parent = parent, body = body, ) return JsonResponse({'body': comment.body, 'user': comment.user.username, 'parent':parent}, safe=False) return JsonResponse({}, safe=False) -
Django Rest Framework - Way to make specific values within two columns in parent table a constraint to be only used together in child table as fk?
not sure I worded my question right in the title, let me try and explain better below... Let's say a parent table called Share has two columns, a ShareCode Charfield(primary key) and a ShareName unique Charfield (string). This means we'll have a unique ShareCode and ShareName paired on each row of this table. Code for this below. class Share(models.Model): ShareCode = models.CharField(max_length=100, primary_key=True, default="N/A") ShareName = models.CharField(max_length=100, unique=True, default="N/A") Now let's say we have a child table, Fund. This table will consist of a FundID Autofield(primary key), a FundCode Charfield, and a FundName CharField. It will also have two foreign keys that reference the Share table, ShareCode and Sharename. Finally, it will have two unique_together constraints, FundCode and ShareCode as the first constraint, and FundCode and ShareName as the second. Code below. class Fund(models.Model): FundID = models.AutoField(primary_key=True) FundCode = models.CharField(max_length=100, default="N/A") FundName = models.CharField(max_length=100, default="N/A") ShareCode = models.ForeignKey(Share, to_field='ShareCode', related_name='fundsShareCode', on_delete=models.CASCADE) ShareName = models.ForeignKey(Share, to_field='ShareName', related_name='fundsShareName', on_delete=models.CASCADE) class Meta: unique_together = ('FundCode', 'ShareCode'), unique_together = ('FundCode', 'ShareName') Couple of things to note at this point, let's imagine that every share that we could possibly need is already in the Share table. The fund table's data however is being manually input … -
django rest framework update user profile
how can update user object with extended profile model, i want to get fields in one object like: { username, email, [...], gender, avatar, } models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): GENDER_CHOICES = (('Male', 'Male'),('Female', 'Female')) user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=6, blank=True, choices=GENDER_CHOICES) avatar = models.ImageField(upload_to=avatar_upload, default='avatars/default.png') serializers.py from .models import Profile from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='user-detail', lookup_field='pk', read_only=True) pk = serializers.IntegerField(read_only=True) class Meta: model = User fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'url') class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('gender', 'avatar',) views.py class UserUpdateView(APIView): def put(self, request, *args, **kwargs): pass -
How get # fragment values from the URL in Django
In my Django website, I want to redirect to an external website, authenticate on this external website and then the external website returns an API token that I want to save. I have instructed the external website to redirect to 127.0.0.1:8000 (my home page) after I have successfully authenticated. When I'm redirected, I have a URL in this format: http://127.0.0.1:8000/#access_token={token the external website generates}&token_type=Bearer&expires_in={expiry time}. How can I get the values after the # in the URL? As I understand the values after the # is not sent back to the Django server. -
Django Model.objects.last() returning second to last instance instead of the very last instance
I'm in the process of building a Django app, which is meant to be a self updating inventory app for a hypothetical restaurant. I have a model, "Purchase", which uses another model "Register" as a ForeignKey field. I have it set the reference to the last instance created of Register so that any entree purchase is linked to the currently active register at the store. The problem is that when a Purchase instance saves, it keeps referencing the second to last Register object instead of the last. Here is the current model code for those two models: class Register(models.Model): daily_bank = models.FloatField(default=500) amount_spent = models.FloatField(default=0) amount_made = models.FloatField(default=0) date = models.DateField(default=date.today) def sales(self): lst = [] for p in self.purchase_set.all(): if p.menu_item not in lst: lst.append([p.menu_item.title, 1]) else: for entry in lst: if entry[0] == p.menu_item.title: entry[1] = entry[1] + 1 return lst def profit(self): if self.id > 1: return self.daily_bank - Register.objects.get(id=self.id-1).daily_bank else: return self.daily_bank - 500 def last(self): return self == Register.objects.last() class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=SET_NULL, null=True) time = models.DateField(default=datetime.now) item_name = models.CharField(max_length=100) register = models.ForeignKey(Register, on_delete=CASCADE, default=Register.objects.last()) def save(self, *args, **kwargs): self.item_name = self.menu_item.title if self.pk is None: for i in self.menu_item.reciperequirment_set.all(): if i.menu_item == … -
Steam API json output isn't being displayed cleanly
I've been trying to get the output from the steam API to display in my django app. My goal is to create a "portfolio" of games that I own for a project - using the information in the Steam API. I'm fairly new to Django, but know enough to be dangerous. Any help would be greatly appreciated, as I have been banging against this for a week... My question is, how does one pull specific items from the json and display the data correctly inside of the template? I cannot seem to loacte a tutorial that fits the schema of the output from this API. - any help (and a brief explanation maybe) would be greatly appreciated. For example, how can I capture the minimum system requirements from the API and display them in a div on my page? This is my views.py: def index(request): response = requests.get('https://store.steampowered.com/api/appdetails/?appids=218620').json() return render(request, 'index.html', {'response': response}) While it actually returns data, you'll notice that the data is littered with weird characters and such. Here is my index.html: {% extends 'base.html' %} {% block content %} {{response}} {% endblock %} if you add a 'safe' tag to the django template like this: {% extends … -
how to use django redirect when we have dynamic url
i have dynamic uls urlpatterns=[path('author/<str:pk>/',views.authorview,name='author')]` and i want to use it in redirect def loginview(request):` `if request.method=='POST':` `username = request.POST.get('username')` `password = request.POST.get('password')` `user = authenticate(request, username=username, password=password)` `if user is not None:` ` login(request, user)` `return redirect('profile')` # i want to use it here else: return redirect('/blogapp/signup/') #context={'username':username,'password':password} return render(request,'blogapp/loginview.html')` i am not able to use this (/str:pk/) on redirect -
Disable Django default colored logs
I'm trying to take advantage of the default Django logging system and save those messages on a file. The only problem is that messages have color codes, that also get saved in the destination file handler. I added a custom file handler with a custom formatter to the "django" logger, but the message is still colored. I tried to debug a bit and I believe that there is some formatter working under the hood that add colors to the messages, since printing the messages received by my formatter shows that they already contain the color codes. I also tried creating a CustomServerFormatter which is a copy of django's default ServerFormatter (in which I saw the color codes were applied), but without the calls to add colors based on the HTTP response, but still no results. This is my current dictconfig: LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": { "()": "django.utils.log.RequireDebugFalse", }, "require_debug_true": { "()": "django.utils.log.RequireDebugTrue", }, }, "formatters": { "django.server": { "()": CustomServerFormatter, "format": "[{server_time}] {message}", "style": "{", }, "syslog_ws": { "()": SyslogFormatter, 'name': "webs" }, }, "handlers": { "console": { "level": "DEBUG", 'filters': ['require_debug_true'], "class": "logging.StreamHandler", }, "file": { "formatter": "syslog_ws", "level": "INFO", "class": "logging.handlers.RotatingFileHandler", "filename": … -
Cannot assign "<SimpleLazyObject: <User: student1@mail.ru>>": "Answer.id_student" must be a "Student" instance
I am trying to use email for authentication in Django. Previously, I worked directly with the user, but I need it through the "Student" class. VIEWS class AnswerToCase(FormMixin, DetailView): STATUS = [ ('Участник', 'Участник'), ('Победитель', 'Победитель')] model = Case template_name = 'addanswer.html' form_class = AddAnswer success_url = '/' context_object_name = 'get_case' def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): self.object = form.save(commit=False) self.object.id_case = self.get_object() What is the correct way to specify saving an object to yourself? self.object.id_student = self.request.user self.object.is_won = self.get_object() self.object.save() return super().form_valid(form) If I write the command like this self.object.id_student = Student.objects.get(user_id=self.request.user) Error ['The value of “Fun” must be True or False.'] Fan is title of the "case" model Models Class User class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) phone = models.CharField(max_length=20, help_text='Номер телефона') is_staff = models.BooleanField(default=True) # must needed, otherwise you won't be at is_active = models.BooleanField(default=True) # must needed, otherwise you won't be « is_superuser = models.BooleanField(default=False) # this field we inherit from Permis is_student = models.BooleanField(default=False) is_partner = models.BooleanField(default=False) objects = CustomUserManager() REQUIRED_FIELDS = ["phone"] USERNAME_FIELD = 'email' Class Student class Student(models.Model): user = models.OneToOneField(User, verbose_name='id', on_delete=models.CASCADE, primary_key=True) Fio = models.CharField(max_length=100, blank=True, … -
ConnectionRefusedError viewing ImageField in admin
absolute django noob here. I've just been choosing some random things that interest me to try to learn more about doing development on the platform. I have tried to add an ImageField to one of my models. If I don't have an image saved as part of the object the admin area displays fine, but if I have tried to save an image (the save doesn't show me any error that I'm aware of - i can see an image path in that field) then when browsing the model in the admin I get a ConnectionRefusedError Internal Server Error: /admin/fb/organization/ Traceback (most recent call last): File "/home/rowc/.local/lib/python3.8/site-packages/django/db/models/options.py", line 672, in get_field return self.fields_map[field_name] KeyError: 'thumbnail_preview' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/rowc/.local/lib/python3.8/site-packages/django/contrib/admin/utils.py", line 271, in lookup_field f = _get_non_gfk_field(opts, name) File "/home/rowc/.local/lib/python3.8/site-packages/django/contrib/admin/utils.py", line 302, in _get_non_gfk_field field = opts.get_field(name) File "/home/rowc/.local/lib/python3.8/site-packages/django/db/models/options.py", line 674, in get_field raise FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: Organization has no field named 'thumbnail_preview' My model looks like so class Organization(models.Model): class Meta: ordering = ['name'] name= models.CharField(max_length=32, unique=True) abbreviation= models.CharField(max_length=3, unique=True) logo = models.ImageField(blank=True, upload_to='images') def __str__(self) -> str: return "(" + self.abbreviation + ") " + self.name @property def … -
Unable to log msgs from Local Django apps to Console when using Docker
I have configured a Django project using cookiecutter-django. When I run this locally I don't see any log from my local Django Apps on the console. Tried several solutions discussed on StackOverflow but nothing worked. What am I missing? The logging was working fine before I dockerised the app. Here's the LOGGING config in settings/base.py (settings.py): LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", } }, "root": {"level": "INFO", "handlers": ["console"]}, "loggers": { "*": { # Tried giving specific local apps name, that didn't work either 'handlers': ['console'], 'level': 'DEBUG', } }, } In the py files I use it like this: import logging logger = logging.getLogger("__name__") logger.error("XXX SOME ERROR MSG XXX") What am I missing? This is such a regular need, wonder how others using cookiecutter-django are working with this! I've already tried the following: print with flush - works when placed in settings/base.py, but doesn't work anywhere else! print("SOME MSG", flush=1) In compose/local/django/start python -u manage.py runserver_plus 0.0.0.0:8000 Added tty=true in local.py services: django: &django tty: true -
Catch errors when connecting to database with Django loggers
I wan't to log errors related to failed connection to the database. For example if I provide it an invalid URL I get the error Traceback (most recent call last): File "/home/vagrant/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/home/vagrant/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/vagrant/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/home/vagrant/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/vagrant/venv/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/home/vagrant/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "wrong-url.com" to address: Name or service not known The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/vagrant/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/vagrant/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check_migrations() File "/home/vagrant/venv/lib/python3.6/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/vagrant/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/vagrant/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/home/vagrant/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/vagrant/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/home/vagrant/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/home/vagrant/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, … -
Uploading files from the frontend to a file server with Python Django and SFTP
I would like to upload files from the frontend (vueJS) with axios to a remote file server. My backend is written in Python and I'm using the Django framework. I successfully uploaded files from the backend to the server with paramiko: sftpclient.put('localpath', 'remotepath') The problem is that it requires the file to be in the backend folder. How can I bypass that and upload the files from the client straight to the file server? I also tried using the django-storages package, but that puts the file in the RAM for some reason and uploads it really slow to the file server (and also crashes when I try it with large files). -
Django Static Files Duplicating when I run collectstatic using heroku's settings
I have a django project that recently started producing a lot of static files. When googling around it seems that I have some overlap in my STATICFILES_DIRS and STATIC_ROOT I followed Heroku's documentation on static files. I noticed it when switching between VScode and pycharm which I do not think could have caused this but I thought i would mention that as well. Pycharm just seems to ignore the 2600 "Unversioned Files" while vs code wants to push them all to github. I do not see the overlap in my static_root and static_dirs and at this point have spent enough time that I thought I would bring it here. Below I have attached images off the errors from heroku and well as the static portion of my settings.py file. Any suggestions of how to keep this from happening and get rid of these ugly bloating files would be greatly appreciated. This is my first deployed site so considering this is my biggest problem now I figure this is a success. But i want these files gone. I also just noticed that when I run mange.py runserver I get two lines of staticfiles -
Django : Get the value from a django Form in the view not working
I wrote a django Form to display a dropdown list of clients. It works and displays correctly the name of the clients and the id in the value of the option tag. However, I can't get the value selected in my view, it prints me a None form.py class SelectClient(forms.Form): ID_Customer = forms.ChoiceField(required=True) def __init__(self, *args, **kwargs) : self.user = kwargs.pop('user') super(SelectClient, self).__init__(*args, **kwargs) id_client_list = TblAadJntGroupmember.objects.filter(id_aaduser=self.user.id).values_list('id_aadgroup', flat=True) id_client_list = list(id_client_list) client_choices = TblAadGroups.objects.all().filter(id__in=id_client_list).values_list('idcustomer','groupname') print(client_choices) self.fields['ID_Customer'].choices = client_choices views.py @authenticated_user def upload(request): # INITIALIZE THE CONTEXT TO FIX THE AUTHENTICATION context = initialize_context(request) username = request.session.get('user').get('name') form_client = SelectClient(request.POST, user=request.user) if form_client.is_valid(): id_customer_request = request.POST.get("ID_Customer") print(id_customer_request) context['form_client'] = form_client return render(request, 'base/upload.html', context) The print of the data from the queryset : <QuerySet [(135, 'Fred Kunz'), (345, 'Lolo Bernard')]> <p><label for="id_ID_Customer">Id customer:</label> <select name="ID_Customer" id="id_ID_Customer"> <option value="135">Fred Kunz</option> <option value="345" selected="">Lolo Bernard</option> </select></p> <input type="submit" value="Select"> -
chaining modelform with foreignkey and display the result on the web page automatically
how to implement auto populated field on Django model form in forms.py. i have a model having a foreign key class and I want to call that element in the -
Feather icons: Uncaught TypeError: r.default[o] is undefined
I use feather icons (https://feathericons.com/) and have Uncaught TypeError: r.default[o] is undefined I did not have before. In some of my templates, it works but in other it raise this error on this line : feather.replace() -
Get html link id in django views.py
This is what my template index.html looks like {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li><a href="{% url 'link' %}">{{ entry }}</a></li> {% endfor %} </ul> {% endblock %} And here is my urls.py file path("link", views.link, name="link") Finally, this is my link view inside of the views.py file def link(request, id): return redirect("page", name=id) Where page() is a function that takes one argument. I want the id of the <a></a> tag of index.html to be that argument. But I have no idea how to access get that id inside of views.py when the <a></a> tag is clicked -
How to dynamically insert a value in a Django ModelForm
I have a project where users can create a company. However, there is a Theme that needs to be dynamically inserted, once the user chooses a theme on the frontend - more like when you want to choose a template in a no-code builder. Below is my models.py class Theme(models.Model): name = models.CharField(max_length=100, null=True) image = models.ImageField(upload_to='static/images/themes_images', null=True, blank=True) category = models.CharField(max_length=200, choices=CATEGORY_CHOICES, null=True) class Company (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, editable=False) date_created = models.DateField(default=timezone.now, null=True) company_name = models.CharField(max_length=100, null=True) theme = models.ForeignKey(Theme, on_delete=models.CASCADE, null=True, blank=True) For the Theme model, it is only the administrator who will create it and the user will only have to choose it on the front end. Sort of like when choosing a premade template in Weebly. All the Theme Objects will have their own page where the user can visually see which theme to go with: @login_required(login_url='login') def theme(request): themes = Theme.objects.all() context = {'themes': themes} return render(request, 'themes.html', context) I haven't done much with the view, cause I am not sure how to go about it to achieve the desired result. Themes.html {% extends 'index.html' %} {% load static %} {% block 'title' %} <title>Themes | Simpledocs</title> {% endblock %} {% block … -
TypeError at /cart/8/My Best Optics/ middleware() got an unexpected keyword argument 'id'
urlpatterns = [ path('cart/<int:id>/<str:sellername>/', auth_middleware(CartViewAndAdd.as_view()) , name='cart'), ] <a href="{% url 'cart' id=price.product.id sellername=price.seller.name %}" class="btn btn-primary">Add to Cart</a> class CartViewAndAdd(View): def get(self , request, id, sellername): customername= '' if('customername' in request.session): customername = request.session['customername'] else: customername = None Was working a few builds back. Dont know what happened -
Fixtures are not working after Django squashmigrations
I just squashed a lot of migrations in Django 4.0.x. Now when running the migrations I get the following error: File "/opt/hostedtoolcache/Python/3.9.10/x64/lib/python3.9/site-packages/Django-4.0.3-py3.9.egg/django/db/migrations/loader.py", line 120, in load_disk migration_module = import_module(migration_path) File "/opt/hostedtoolcache/Python/3.9.10/x64/lib/python3.9/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 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 846, in exec_module File "<frozen importlib._bootstrap_external>", line 983, in get_code File "<frozen importlib._bootstrap_external>", line 913, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/runner/work/backend/backend/general/migrations/0001_squashed_0019_merge_0018_auto_20220226_2311_0018_auto_20220228_2343.py", line 42 code=general.migrations.0004_initial_general.Migration.load_data, ^ SyntaxError: invalid decimal literal The according code lines in the migration file is: migrations.RunPython( code=general.migrations.0004_initial_general.Migration.load_data, ), I am totally lost here.