Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Combining Context Values (filter and queryset) - Python - Django Views - Filter and User
I need to combine two context values in my views.py for my python Django website. One is a filter at the top of the screen that filter all displayed data below and it looks like this... context['filter'] = Sheet_Building_Filter(request.GET, queryset=Sheet_Building.objects.all()) The other is not a page filter but it filters and returns all the data that is from the user that is currently logged in and it looks like... context['user'] = Sheet_Building.objects.filter(user=request.user) I need to combine these to loop through both of them in HTML at the same time. I thought something like this would work but it didn't... context['user_and_filter'] = Sheet_Building_Filter(request.GET, queryset=Sheet_Building.objects.filter(user=request.user)) This just displays the data and doesn't show the filter itself. I'm not sure if the filter works but isn't displaying the fields to filter by or if it is just not working at all. Im not sure why and I can't find any information of a filter and user data is combined into one value. I need it combined because I can't do a nested for-loop in HTML. Code below. Thanks! views.py def listdata_building(request): sheet = Sheet_Building.objects.all() context = {"sheet": sheet} context['user_and_filter'] = Sheet_Building_Filter(request.GET, queryset=Sheet_Building.objects.filter(user=request.user)) context['user'] = Sheet_Building.objects.filter(user=request.user) return render(request, 'sheets/individual/list_data_building.html', context) models.py class Sheet_Building(models.Model): user … -
Is it a good practice to create several one2one fields using signals during user registration? Is there a better way?
Hey guys I have six models that have OneToOne relation with account model and are being created with signals at the time when a user register on the website? Is this a bad practice when there are more number of users? Is there a better way to do it? Should I use celery or some other method to create those models which are of less significance (comparatively) ? Please do let me know. Thanks in advance. -
Add Profile picture to Django Custom User model(AbstractUser)
I have used a custom user model to overwrite username with email-id. Now I want to add an extra field that profiles pictures. I tried extending the model in models.py with the OnetoOne relationship. It works but as I am passing forms to update and create views (Class-based views) to update and create. is there any way to add a profile picture field without creating a model with the OnetoOne relationship? models.py class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email,profilepicture, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User model.""" username = … -
Crypto module and Encryption method not working
Basically, my question is divided into two problems, first of all, I am having this problem when I try running this code [code below] and get an error, like this: ImportError Traceback (most recent call last) <ipython-input-3-3d0c04910b61> in <module> 1 import hashlib ----> 2 from crypto import Random 3 from crypto.Cipher import AES 4 from base64 import b64encode, b64decode 5 ImportError: cannot import name 'Random' from 'crypto' (C:\Users\Ahmad\anaconda3\lib\site-packages\crypto\__init__.py) The second problem is when I enter text, i.e: "My data is here" I got the encrypted text as : "GIdd+zxj8m0nMeh7wmZJ+Q==" but reversing the process in decryption it outputs a different text, to validate the process I am using and checking through https://aesencryption.net/ as reference in my work. My Code: import hashlib from crypto import Random from crypto.Cipher import AES from base64 import b64encode, b64decode class AESCipher(object): def __init__(self, key): self.block_size = AES.block_size self.key = hashlib.sha256(key.encode()).digest() def encryption(self, plain_text): plain_text = self.__pad(plain_text) iv = Random.new().read(self.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) encrypted_text = cipher.encrypt(plain_text.encode()) return b64encode(iv + encrypted_text).decode("utf-8") def decryption(self, encrypted_text): encrypted_text = b64decode(encrypted_text) iv = encrypted_text[:self.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) plain_text = cipher.decrypt(encrypted_text[self.block_size:]).decode("utf-8") return self.__unpad(plain_text) def __pad(self, plain_text): number_of_bytes_to_pad = self.block_size - len(plain_text) % self.block_size ascii_string = chr(number_of_bytes_to_pad) padding_str = number_of_bytes_to_pad … -
How do I make a track report from my Django models in a way that the report also has its auto-incremented primary key?
I have 3 models: class Student(models.Model): roll_number=models.IntegerField(primarykey=True) name=models.CharField(max_length=50) email=models.EmailField(max_length=60) city=models.CharField(max_length=20) class Course(models.Model): roll_number=ForeignKey(Student, on_delete=CASCADE) course=ForeignKey(CourseChoices, on_delete=CASCADE) class Fee(models.Model): roll_number=ForeignKey(Student, on_delete=CASCADE) amount_to_be_paid=models.DecimalField(max_digits=7, decimal_places=2, default=0) discount=models.DecimalField(max_digits=5, decimal_places=2, default=0) Final_amount_to_be_paid=models.DecimalField(max_digits=5, decimal_places=2, default=0) Amount_received=models.DecimalField(max_digits=5, decimal_places=2, default=0) Balance=models.DecimalField(max_digits=5, decimal_places=2, default=0) batch=models.CharField(validators=[batch_pattern]) Now, whatever data these tables hold, I want to display them together as: I want each and every transaction to be tracked by a separate track id. The track id should be auto-incrementing, unique key. How do I achieve this? I tried creating one more model while applying multiple inheritance on it but It clearly couldn't work. That way, the user would have to enter the data in the table created by the last model where all the fields would be available to fill but the scenario cannot allow this as each forms would be filled on separate days, not at once. So the complete information are to be entered separately, so forms are divided. But I want them together to track each transaction with a track ID. I'm a beginner and just trying stuffs here but I'm constantly failing since almost a week now. Any suggestions, please!! Thanks for your help! -
Не запускается локальный сервер Django [closed]
Установил Django через pip. Пытаюсь запустить локальный сервер Django командой python manage.py runserver , но получаю ошибку. Проект только создал. В чем может быть проблема ? Traceback (most recent call last): File "C:\Users\albor\First\manage.py", line 22, in <module> main() File "C:\Users\albor\First\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 96, in handle self.run(**options) File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 640, in run_with_reloader exit_code = restart_with_reloader() File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 259, in restart_with_reloader p = subprocess.run(args, env=new_environ, close_fds=False) File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\site-packages\run\__init__.py", line 145, in __new__ process = cls.create_process(command, stdin, cwd=cwd, env=env, shell=shell) File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\site-packages\run\__init__.py", line 121, in create_process shlex.split(command), File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\shlex.py", line 315, in split return list(lex) File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\shlex.py", line 300, in __next__ token = self.get_token() File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\shlex.py", line 109, in get_token raw = self.read_token() File "C:\Users\albor\AppData\Local\Programs\Python\Python39\lib\shlex.py", line 140, in read_token nextchar = self.instream.read(1) AttributeError: 'list' object has no attribute 'read' -
How i can get user's browser timezone using django 3.2?
I have my small django project and I want to get user's timezone, how I can do this. -
How can I model a database view in Django if it doesn't have a primary key?
I have a database view that relates 2 companies by foreign keys like so: DB company_view: company1_id FK to Company, company2_id FK to Company, some_description text I try model in Django as unmanaged like so: class CompanyView(models.Model): company1 = models.ForeignKey(Company, related_name='company1_id', parent_link=True) company2 = models.ForeignKey(Company, related_name='company2_id', parent_link=True) class Meta: managed = False db_table = 'company_view' But it throws exception like: psycopg2.errors.UndefinedColumn: column company_view.id does not exist It doesn't make sense to have a primary id key, so is there any way around this? Thanks -
Python: Calculate time between current time and last login. (Automated Communication)
I'm trying to make a celery task that would send a basic reminder to our users. So in our automated communication project, we have these tasks: As you can see there are few actions that are different. So for now I have created a logic that fetches all the users from the DB and then continues by checking the time difference. But for now, I only have set-up for 2 hours or more. How should I use it correctly? I do not want to re-write each if statement because it's bad practice. How should I make it clear and reduce the system load? @app.task def check_registered_users(): from apps.users.models import User from apps.notifications.models import AutomatedCommunicationNotifications day_start = datetime.utcnow().date() day_end = day_start + timedelta(days=1) users = User.objects.filter(is_active=True, date_joined__range=(day_start, day_end)) users_that_received_notification = AutomatedCommunicationNotifications.objects.all().values('user__id') excluded_users = users.exclude(id__in=users_that_received_notification) for user in excluded_users: if user.last_login < user.last_login + timedelta(hours=2): # Sign-up uncompleted Push notification 2 hours after last login template = SiteConfiguration.get_solo().automated_comms_signup_uncompleted send_plain_email_task( email=user.email, subject=template.subject, html_message=template.content, from_email=f'{settings.EMAIL_FROM_PREFIX} <{settings.DEFAULT_FROM_EMAIL}>', ) -
How can I make the get_random_string Django module to return only numerical values?
What should I do to my simple code below, so that it only returns numerical values? >>> from django.utils.crypto import get_random_string >>> get_random_string(10) >>> 'PhaWT9X02U' Something like: 1067603657 And if it is possible, can you recommend an id field generated in this manner? -
How is PUT request handled in Django REST Framework?
I need to clarify how DRF works. Imagine there's a Django REST Framework application that manages two ressources: departments and employees: class Department(models): name = models.CharField(primary_key=True) class Employee(models): name = models.CharField() dept = models.ManyToManyField() with serializers: class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = ('name', ) class EmployeeSerializer(serializers.ModelSerializer): dept = DepartmentSerializer class Meta: model = Employee fields = ('name', 'dept', ) Requesting (GET /employees/1) an employee returns the department as a nested object, which is good. What does DRF do, when I send PUT /employees/1 { "department": "sales" } Which part of the program does this request go through? I would assume First using dispatching a view is selected In the update Method (if overwritten) of the view, I can assign a serializer The request and Primary Key of the target are available through self.request and pk of the method handler What I end up doing now is to write a bloated update method, which kind of does not feel the way it should be where I check for every attribute if it is in the request and if yes than update it. def update(self, request, pk=None): employee = Employee.objects.get(pk=pk) if self.request.data.get("name"): employee.name = self.request.data.get("name") if self.request.data.get("dept"): employee.dept.add(self.request.data.get("dept") employee.save() … -
django-autocomplete-light template not rendering autocomplete widget
I am trying to make a search field on my homepage where you search entries by tag, and within that search field as you type in letters it should suggest you tags that contain what you have typed so far. I am using django-taggit for tags. I have followed this tutorial : https://django-autocomplete-light.readthedocs.io/en/master/taggit.html It has support for django-taggit. template <div class="search-container"> <form method="post"> {% csrf_token %} {% for field in form %} {{ field.label_tag }} {{ field }} {% endfor %} <button type="submit">Search</button> </form> </div> urls.py # AUTOCOMPLETE URL url(r'^tag-autocomplete/$', views.TagAutocomplete.as_view(), name='tag-autocomplete'), forms.py class SearchForm(autocomplete.FutureModelForm): class Meta: model = Intrare fields = ('tags',) widgets = { 'tags': autocomplete.TaggitSelect2('intrari:tag-autocomplete') } models.py class Intrare(models.Model): tags = TaggableManager() def __str__(self): return self.titlu views.py class TagAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): intrari = [intrare.tags for intrare in Intrare.objects.filter(public=True)] tags = reduce(lambda x, y: x | y, [tags.get_queryset() for tags in intrari]) tags = [tag.name for tag in tags] qs = Tag.objects.filter(name__in=tags) if self.q: qs = qs.filter(name__contains=self.q) return qs Here is the result. The widget does not show properly -
Password is displayed as text in the admin panel (not hashed)
There is a CustomUser model inherited from AbstractUser. When registering a model in the admin panel, the password is displayed as text, that is, the type of this field is text, not password. I know that this problem can be solved if, together with the model, the ModelAdmin class is registered, in my case it will be CustomUserAdmin inherited from UserAdmin from django.contrib.auth.admin, and the password will be displayed correctly, but then the fields from CustomUser will not be displayed (as if the CustomUser model is registered, but only the fields of the User model will be displayed, when using a class inherited from the above-mentioned UserAdmin). What to do with this, please tell me! -
Python list value show in html table
Following show my python return: return render(request,'school\Views\Spredictions.html'{'len':length,'final':Ol_result,'data':marks_sheet}) Here, final : - ['pass','pass',''fail,'fail'] like this following show the my html code <tbody> {%for m in data%} <tr> <td>{{m.student_name}}</td> <td>{{final}}</td> </tr> {%endfor%} </tbody> I want to show one by one value in table interface, but show like that output of table How to solve this problem. Any one can help me Thank you -
Annotating single model instance (instead of queryset) in django
So, I have a Post model which contains PostVotes from users class Post(models.Model): voters = models.ManyToManyField(User, through="PostVote") #other stuff and the post vote can have a state of either "upvote" or "downvote" (I know I should be using enums or a bool for this before I start receiving those comments) and in many cases I need to count the total score of the object for the frontend. When I have the posts in a queryset, the following solution is working well: posts = Post.objects.all().annotate(vote=models.Sum( models.Case( models.When(postvote__state="upvote", then=1), models.When(postvote__state="downvote", then=-1), default=0, output_field=models.IntegerField() ) )) However, there are many cases where I want to do a similar thing but instead of a queryset I have just a single instance. How do I do this? Trying the above solution gives 'Post' object has no attribute 'annotate' -
Update model data after javascript alert button click - Django
I have a javascript alert (It uses swal to style it, but it functions like a regular alert). I want to run SomeModel.objects.filter(id=id).delete() after the ok button is clicked. How exactly can I do this? My JS is down bellow. swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } Views.py: def acceptdonation(request): donations = Donation.objects.all() context = {} return render(request, 'acceptdonation.html', context) -
DJANGO REST FRAMEWORK IMAGE UPLOAD ["The submitted data was not a file. Check the encoding type on the form."]
I can't seem to upload an image to my project. I always get this error when i try to submit the form from the frontend : ["The submitted data was not a file. Check the encoding type on the form."] I've found some answers regarding the base64 encoding of the image but i can't seem to get it to work. Any help would be much appreciated!! thanks here is the source code: Models: class Person(models.Model): name = models.CharField(max_length=30) age = models.IntegerField(default=0) dob = models.CharField(max_length=10) image = models.ImageField(upload_to='images/', null=True) def __str__(self): return self.name class Details(models.Model): party = models.ForeignKey(Person,on_delete=models.CASCADE, related_name='party_details',null=True,blank=True) adress = models.CharField(max_length=50) date = models.CharField(max_length=20) arrival= models.CharField(max_length=20) def __str__(self): return self.adress Serializers: class DetailsSerializer(serializers.ModelSerializer): class Meta: model = Details # fields='__all__' fields = ('id','party','adress','date','arrival') class PersonSerializer(serializers.ModelSerializer): party_details =DetailsSerializer(many=True) class Meta: model = Person # fields='__all__' fields = ('id','name','age','dob','image','party_details') def create(self, validated_data): named_details = validated_data.pop('party_details') details = Person.objects.create(**validated_data) for named_detail in named_details: Details.objects.create(party=details, ** named_detail) return details def update(self,instance, validated_data): named_details = validated_data.pop('party_details') details = (instance.party_details).all() details = list(details) instance.name = validated_data.get('name', instance.name) instance.age = validated_data.get('age', instance.age) instance.dob = validated_data.get('dob', instance.dob) instance.image = validated_data.get('image', instance.image) instance.save() for named_detail in named_details: detail = details.pop(0) detail.adress = named_detail.get('adress',detail.adress) detail.date = named_detail.get('date',detail.date) detail.arrival = named_detail.get('arrival', … -
UnboundLocalError ,local variable 'order' referenced before assignment
i am trying to create an ecommerce website and i want to create an order for the user,however, i got an error saying that the order is referenced before assignment but i cant understand it . kindly advise the way to solve it. Thank you i am trying to create an ecommerce website and i want to create an order for the user,however, i got an error saying that the order is referenced before assignment but i cant understand it . kindly advise the way to solve it. Thank you def add_to_cart(request, pk): product = Product.objects.get(id=pk) order_item,created = OrderItem.objects.get_or_create( product =product, user = request.user, ordered = False, ) order_qs = Order.objects.filter(user=request.user,ordered=False) if order_qs.exists(): order =order[0] if order.items.filter(product__id=pk).exists(): order_item.quantity +=1 order_item.save() messages.info(request ,"Added additional worker successfully") return redirect("ecom:product_desc",id=pk) else: order.items.add(order_item) messages.info(request ," successfully booked") return redirect("ecom:product_desc" ,id=pk) else: ordered_date =timezone.now() order =Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request," Successfully booked") return redirect('product_desc',id=pk) #context ={'desc':desc} return render(request ,'products/desc.html',context) below is the error message i got.please advise how i can fix this error model.py file class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default =1) def __str__(self): return f"{self.quantity} of {self.product.name}" def get_total_item_price(self): return self.quantity * self.product.price def get_final_price(self): … -
Issues with JSONField order_by querying fields with punctuations in the name
I'm trying to query my DB for a JSONField that I have and I want to order it by the highest core amount. The issue i'm facing is that I have punctuations in the JSON objects name, and it returns an error in Django. I'm a bit unsure how to approach this issue. Query: db = Node.objects.all().order_by("data__golem.inf.cpu.cores") Model: class Node(models.Model): node_id = models.CharField(max_length=42, unique=True) wallet = models.CharField(max_length=42, null=True, blank=True) earnings_total = models.FloatField(null=True, blank=True) data = models.JSONField(null=True) online = models.BooleanField(default=False) version = models.CharField(max_length=5) updated_at = models.DateTimeField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) Example of the data: { "earnings_total": 20.476530214728843, "node_id": "0x189e2688456c08efdc578250ef64044dc5fed245", "data": { "id": "0x189e2688456c08efdc578250ef64044dc5fed245", "wallet": "0x10c830138690e335d315f135d7a09728239c4512", "golem.com.scheme": "payu", "golem.inf.mem.gib": 61.35306134819984, "golem.node.id.name": "ea26j8x2r712", "golem.runtime.name": "wasmtime", "golem.inf.cpu.cores": 16, "golem.inf.cpu.threads": 32, "golem.inf.storage.gib": 32.920249938964844, "golem.runtime.version": "0.2.1", "golem.com.usage.vector": [ "golem.usage.duration_sec", "golem.usage.cpu_sec" ], "golem.com.pricing.model": "linear", "golem.node.debug.subnet": "public-beta", "golem.inf.cpu.architecture": "x86_64", "golem.srv.caps.multi-activity": true, "golem.com.scheme.payu.interval_sec": 120.0, "golem.activity.caps.transfer.protocol": [ "https", "http", "gftp" ], "golem.com.pricing.model.linear.coeffs": [ 0.0, 0.00017602265896846447, 0.0 ], "golem.com.payment.debit-notes.accept-timeout?": 240, "golem.com.payment.platform.erc20-mainnet-glm.address": "0x10c830138690e335d315f135d7a09728239c4512", "golem.com.payment.platform.zksync-mainnet-glm.address": "0x10c830138690e335d315f135d7a09728239c4512" }, "online": true, "version": "0.7.1", "updated_at": "2021-07-23T13:11:59.294294+02:00", "created_at": "2021-06-08T20:54:34.951232+02:00" }, Traceback: File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/asgiref/sync.py", line 444, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/local/lib/python3.9/asyncio/tasks.py", line … -
What is wrong in if request.method == 'POST'
Please what I am doing wrong in this function of Django ? def notification_read(request, pk): if request.method == 'POST': notification = get_object_or_404(Notification, pk=pk, viewed_at=None, user=request.user) form = NotificationForm(request.POST, instance=notification) if form.is_valid(): notification.viewed_at = timezone.now() notification.save(update_fields=['viewed_at']) form.save() return redirect('users:notification') How can I do this better ? Can anybody can explain, why it does not working good? -
Django. Go from one admin page to another
I'm completely new in Django. I have a large project. I need to add a feature: bulk edit using django admin panel. I figured out how to make another action, but I don't understand how to redirect a user from one admin page to another. How can I achieve this? My action function: def apply_to_brands(modeladmin, request, queryset): mymodels = django.apps.apps.get_model(app_label='brand', model_name='Brand') brands = Brand.objects.all() data = { 'brands': brands, } return HttpResponse()<--- Here I need some logic that redirects me to another admin page and preserves info that queryset contains. -
before learning Django, should I learn SQL or MongoDB?
I want to learn Django, do I need to learn SQL or MongoDB before learning Django. any help please cause I am so confused -
why I am Getting 500 error with javascript
good day, I am using Javascript to make "PUT" method to my python3 models and I am using Django Framework Below is my Javascript function loadit(id,state){ fetch(`/user/loadpigeon/${id}`, { method: "PUT", body: JSON.stringify({ loaded: !state, }), }); alert(id + " Successfully loaded" + state + "lap:ID" );} urls.py path("loadpigeon/<int:id>/", views.load_pigeon, name="loadpigeon"), views.py def load_pigeon(request, id): if request.method == "PUT": pigeon = Mypigeons.objects.get(owner=request.user ,pk=id) data = json.loads(request.body) if data.get("loaded") is not None: pigeon.loaded = data["loaded"] pigeon.save() return render(request, 'user/add.html') #return HttpResponse(status=204) on my html console I am getting this message: Failed to load resource: the server responded with a status of 500 (Internal Server Error) -
dj-rest-auth token user authorization problem
I am begginer who needs some help. I made custom token authentication, where token was stored in localStorage with expiration date, then to know if user is logged I just check if token exists - simply as that. However now I want to use dj-rest-auth to make things easier. After loggin in with form (username, password fields) I can not figure how to check if user has logged in or redirect him from login page. Can someone help me and give phrase to search because I dont get it at all and cant find exact tutorial or just sample code. I can get token and save it to local storage const handleClick = (e) => { console.log(state.username, state.password); e.preventDefault(); axios .post("http://127.0.0.1:8080/auth/login/", { username: state.username, password: state.password, }) .then((res) => { console.log(res.data.key); window.localStorage.setItem("Token", res.data.key); }) .catch((err) => console.log(err)); and then use it (I guess) import SignIn from "./containers/SignIn"; import axios from "axios"; import { useEffect, useState } from "react"; export default function App() { const [data, setData] = useState([]); const [isVisible, setIsVisible] = useState(false); const token = localStorage.getItem("token"); useEffect(() => { axios .get("http://localhost:8080/api/product-list/", { headers: { Authorization: `Token ${token}` }, }) .then((res) => { setData(res.data); }); }, []); const handleClick = … -
Combine one-to-one and many-to-many (django)
I have a model named "db_connector" and another one "project_site". A "project_site" can have many to many relation with "db-connector". But the "project_site" should have one default db-connector. What is the best design-pattern for this? Can I combine many to many and one to one like this: Many to many relation for alternative connectors linked to a project_site and one to one for the default connector linked to a project_site?