Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to retrieve the value of the argument passed through the URL
I am trying to learn Django by working on a small project. The website has 3 buttons on the home page (Home.html). Each button represents a type of user. Upon clicking a button, the user is taken to the signup page. In the GET request to the Signup page, a variable named user_type is set based on the value of the button that was clicked on the home page. The variable is passed on to the Signup.html template and is used as a parameter for the POST request. My intention is to use this parameter from the URL in my signup view and set the database field named user_type. But I am unable to retrieve the value of the parameter in the view. I get an empty string when I print u_type. Even though the URL in the browser shows the value of user_type. Kindly help me with this issue. I am also open to trying alternate ways to achieve the same results. view.py from django.shortcuts import render from django.http import HttpResponse from .forms import SpaceUserForm from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required def home(request): return render(request, 'Users/Home.html') def signup(request, u_type=''): if request.method == 'POST': form = SpaceUserForm(request.POST) … -
how to retrieve the token generated while using django allauth and django-rest-auth with django rest framework
I am using django allauth and django-rest-auth from this tutorial to generate a token for django rest framework. The tutorial can be found on this page, at the bottom. (https://www.softcover.io/read/92780ad5/django_book/token_authentication) I am able to generate the token after accessing api/dj-rest-auth/register/, which is the sign up page from the browsable API. Now the issue is that i am on python3 manage.py shell and i am trying to retrieve any of the token generated for either user test001 or test002 does any one know how to do it? I am having a hardtime to achieve it Thanks in advance -
Django Creating a custom user model
Hello i am trying to create a custom user model (that inherit from User) to make the user to put their email rather than usernames, and i am getting an error in settings.py, I have no idea about CustomUser app, but i am trying to figure out if we can include this as an app inside settings.py, the code and traceback: models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user 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) extra_fields.setdefault('is_active', 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 Ticket(models.Model): email = models.EmailField(max_length=255) title = models.CharField(max_length=250) desc = models.TextField(max_length=99999) class RespondToTicket(models.Model): name = … -
django-admin startproject doesn't work (macOS Big Sur)
Able to install and create projects with older version of Django(2.1.5), but with the latest version of Django, I got errors when running django-admin startproject project-name: Traceback (most recent call last): File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/bin/django-admin", line 8, in sys.exit(execute_from_command_line()) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/init.py", line 419, in execute_from_command_line utility.execute() File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/init.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/commands/startproject.py", line 19, in handle options['secret_key'] = SECRET_KEY_INSECURE_PREFIX + get_random_secret_key() File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/core/management/utils.py", line 82, in get_random_secret_key return get_random_string(50, chars) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/utils/crypto.py", line 72, in get_random_string return ''.join(secrets.choice(allowed_chars) for i in range(length)) File "/Users/me/.local/share/virtualenvs/dapi-dD6sgvz-/lib/python3.9/site-packages/django/utils/crypto.py", line 72, in return ''.join(secrets.choice(allowed_chars) for i in range(length)) AttributeError: module 'secrets' has no attribute 'choice' -
django 3.2- error creating superuser in sqllite3
PS C:\Users\Abdulla Zia\PycharmProjects\EnhanceImage> python manage.py createsuperuser Username (leave blank to use 'abdullazia'): admin Email address: Password: Password (again): Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 157, in handle validate_password(password2, self.UserModel(**fake_user_data)) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\password_validation.py", line 44, in validate_password password_validators = get_default_password_validators() File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\password_validation.py", line 19, in get_default_password_validators return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\password_validation.py", line 30, in get_password_validators validators.append(klass(**validator.get('OPTIONS', {}))) File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\auth\password_validation.py", line 174, in __init__ with gzip.open(password_list_path, 'rt', encoding='utf-8') as f: File "C:\Users\Abdulla Zia\AppData\Local\Programs\Python\Python37\lib\gzip.py", line 57, in open raise TypeError("filename must be a str or bytes object, or a file") TypeError: filename must be a str or bytes object, or a file performed all the migrations still getting this error. I've deleted database file and created new one still getting the same error. server is up and in running without any errors -
Django random css names
I want the background color to change every time with Django. For example: bg-success, bg-primary, bg-light, bg-dark... etc. and just randomly. How can I do? <div class="bg-success"> </div> -
passing a tuple in a Google charts table using Django
Good afternoon everyone, I am implementing Google Charts API in my Django project. I would like to draw two different charts, a pie chart and a table chart. I am able to display the Pie chart without problems. However, I am having trouble with the table chart. I am passing a tuple to the data.setCell() method. When I do that the table chart does not render. Hereunder is the code that I wrote: function drawTable() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Company Name'); data.addColumn('number', '52 week high'); data.addColumn('number', '52 week low'); data.addRows(5); {% for company in data_cell|safe %} data.setCell(company); {% endfor %} // data.setCell(0, 0, 'John'); var table = new google.visualization.Table(document.getElementById('table_div')); table.draw(data, {showRowNumber: true, width: '50%', height: '50%'}); google.visualization.events.addListener(table, 'select', function() { var row = table.getSelection()[0].row; alert('You selected ' + data.getValue(row, 0)); }); } data_cell is a variable that contains a list of tuples and it is part of the context dictionary in my views.py file. As follows you can find an example; ('Facebook', 384.33, 244.61) I have tried looping through the list of tuples without the safe method and it does not work. Any hints? -
Is escapejs filter is enough for public submitting fields like blog?
Is escapejs filter is enough for public submitting fields like blog? I am using escapejs and escape filters to protect fields from XSS attacks. -
What's an alternative to webapp2?
I am working with an old python2 code that used webapp2 module but I need to build an app for app engine flex environment that uses python3, so I am thinking of using an alternative package to webapp2, can someone please suggest a simple to use alternative to webapp2 that works with python3 and does exactly same thing? Thanks in advance! -
How to pass Django context variables into JavaScript function?
I have a function in Django views.py which passes a context variable called "queues" into an HTML page. In the HTML page, I have a button where if I click it, it should pass the context variable "queues" into a JavaScript function func. However, as shown in the image attached, I see some errors with the way I am doing this. What is the correct syntax to do this? HTML code -
DateTimeInput() widget putting a random T in between Date and Time, causing ValidationError
I have a datetimefield, which I am inputting data using the following form field: delivery_pickup = forms.DateTimeField(label = "Delivery or Pickup Appointment", required = False, widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) A nice little datetime widget appears automatically due to the type attribute declaration. The problem is when I try to submit using the widget, I get an error, and when I remove the widget and look at the input as a simple string, it includes a random T in between the date and the time, like so: 2021-09-26T13:17 Removing the T manually causes the error to go away. What's the best way to remove the T? Is it by formatting the string within the input field? Creating a clean method? Some other technique? Any help is appreciated. -
Annotations multiplication with filtering on many to many relationship
I have models: class Tag: name class User: tags = M2M to Tag ... class Bill: id tags = M2M to Tag ... class BillRow: bill = FK to Bill, related_name='rows' quantity ... And I want for an User filter the Bills on Tags and annotate with some aggregates, for example Count of rows, Sum of quantity... Bill.objects.filter(tags__in=user_tags).annotate(row_count=Count("rows")) The problem is that if User and Bill have more tags in common (some User U1 has user_tags ['T1', 'T2', 'T3'] and some Bill B1 has ['T2', 'T3', 'T4']) the resulting query is using an inner join on the Tag table for the filter and it duplicates in this example the row_count annotation, because for each row of B1 there are 2 joined rows (for both of the shared tags) which satisfy the condition. Is there some solution for this type of annotation specifically in Django ORM, but more broadly what would be the optimal approach in SQL to obtain the correct results? -
Server Error 500 while authentication | Django
Having server error 500 when trying to save user record and authenticating him to the dashboard. CODE user_id = 5 unique_username = "kashif" user = User.objects.get(pk=user_id) user.unique_username = unique_username user.is_active = True useremail = user.email user.save() user = auth.authenticate(request, email=useremail, password=password) auth.login(request, user) return redirect('home') EROOR Server Error (500) CODE EXPLANATION In above code, user email is already stored in database. Also, Django default login from username is overridden with Email. So here, getting username from user and from already stored email and password and then authenticating user. But having error on authentication line. NOTE Project is uploaded at app.barter.monster -
Has many categories without duplicates across parent
I have three models class Offer: class OfferBonus: offer_bonus_category = models.ManyToManyField(OfferBonusCategory) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, blank=True, null=True) class OfferBonusCategories: category_title = models.CharField(max_length=60,null=True, blank=True) category_description = models.TextField(null=True, blank=True) Each offer may have multiple OfferBonuses and each OfferBonus may have multiple OfferBonusCategories. Offer 1 may have one bonus in Categories A and B and another bonus in categories C and D. Offer 1 cannot have an OfferBonus in both A and C and another OfferBonus in B and C. The existence of the first OfferBonus in A and C would prevent a subsequent OfferBonus added in A or C when adding in the Admin interface. So my question is how to restrict the OfferBonus so that it considers the other records within the Offer so that each OfferBonusCategory can only be used once across all OfferBonus. Is there a way to do this out of the box in Django Admin where the displayed Categories would be disabled on subsequent addition of records? If it needs to be custom, could you please direct me to the "right path"? I am new to Python and Django so I'm not sure what to search for. -
django accent caracter in field
I want to add an accent to my field name . if I do it django w'ill considerated as another field .enter image description here -
pass a value to a pop-up window Django
I have some some description and want get its in my pop-up window. Then I click on div with type button I must get value in pop-up <div class="content-wrapper bg-white"> <!-- container --> <div class="container-fluid"> <div class="page-body inner-page"> <div class="row"> <div class="col-xs-12 col-sm-6"> <div class="inner-page-header"> <div class="col-xs-12 col-sm-4 col-lg-3" style="margin-bottom: 25px; mso-hide: all"> {% if text.description %} <div class="col-xs-12" type="button" data-toggle="modal" data- target="#exampleModal" > {{ text.description }} </div> {% endif %} </div> </div> </div> </div> </div> </div> </div> this component of code from where I must to get {{ text.description }} But my modal window is in base.html and I don't know how must bubble {{ text.description }} which change dynamical (I want- then I click on some of them - in modal window get {{ text.description }} exactly it's. <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% if text.description %} {{ text.description }} {% endif %}} </div> <div class="modal-footer"> <button type="button" data-dismiss="modal" >Close</button> </div> </div> </div> </div> Please help me -
specific attribute from an object will be randomly show on template
I have tried to show an specific attribute values randomly. Just dictionaries are appeared in my web page which I have showed. I want to show the actual questions which are stored in my Question model class Exam(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,related_name='exam_user') subject=models.ForeignKey(Subject,on_delete=models.CASCADE,related_name='exam_subject',default=True) choices={ (1,'QUIZ'), (2,'MIDTERM'), (3,'FINAL') } exam_type=models.IntegerField(choices=choices) exam_mark=models.IntegerField() question=models.ManyToManyField(Question,related_name='exam_question') exam_date=models.DateTimeField(auto_now_add=True) class Meta: ordering=('-exam_date',) def __str__(self): return 'Exam-type'+'-'+str(self.exam_type) `````````````````````````````````````````````````````````````````````````````` class Question(models.Model): subject = models.OneToOneField(Subject,on_delete=models.CASCADE, related_name='question_subject') question_title=models.CharField(max_length=5000,unique=True) option_first=models.CharField(max_length=100,default='') option_second=models.CharField(max_length=100,default='') option_third= models.CharField(max_length=100,default='') option_fourth= models.CharField(max_length=100,default='') mark=models.IntegerField() def __str__(self): return (self.question_title)+'--1--'+str(self.option_first)+'--2--'+str(self.option_second)+'--3--'+str(self.option_third)+'--4--'+str(self.option_fourth) this is my view where I have create a query and passing this to my template def showExam(request,id): exam_list = Exam.objects.filter(id=id) questionlist=Exam.objects.filter(id=id).order_by('?').values('question').distinct() dict={'exam':exam_list,'questionlist':questionlist} return render(request,'question_app/showExam.html',context=dict) <table class="table table-bordered table-striped "> <tr> <th>Exam Type</th> <th>User Id</th> <th>Question List</th> <th>Exam Mark</th> <th>Exam Date</th> </tr> {% for row in exam %} <tr> <td>{{ row.exam_type }}</td> <td>{{ row.id }}</td> <td> {% for qes in questionlist %} <ol>{{ qes }}</ol> {% endfor %} </td> <td>{{ row.exam_mark }}</td> <td>{{ row.exam_date }}</td> </tr> {% endfor %} </table> In the image there are some questions which are randomly appeared but the real questions in this dictionaries cant be fetched from it -
Exclude child in nested serializer
I have three serializers: class BookingSerializer(serializers.ModelSerializer): owner = serializers.CharField(source="owner.username", read_only=True) class Meta: model = Booking fields = ( "id", "createdDate", "comments", "location", "date", "operator", "status", "owner", ) class CompanySerializer(serializers.ModelSerializer): bookings = BookingSerializer(many=True, read_only=True) owner = serializers.CharField(source="owner.username", read_only=True) class Meta: model = Company fields = ("id", "name", "description", "location", "bookings", "owner") class UserSerializer(serializers.HyperlinkedModelSerializer): bookings = BookingSerializer(many=True, read_only=True) companies = CompanySerializer(many=True, read_only=True) class Meta: model = User fields = ("url", "id", "username", "email", "bookings", "companies") UserSerializer return the all the fields, but the bookingserializer is called twice. { "url": "http://localhost:8000/users/4/", "id": 4, "username": "test", "email": "test@test.com", "bookings": [ { ... } ], "companies": [ { ... "bookings": [ { ... } ] } ] } How do I exclude the bookings field in companies when using UserSerializer? I would still like to have CompanySerializer return bookins in other cases. Thanks! -
Django REST Frameworking overfetching when using PrimaryKeyRelatedField
My Django model: class Quest(models.Model): name = models.CharField(max_length=255) is_completed = models.BooleanField(default=False) characters = models.ManyToManyField(Character, blank=True) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) The DRF serializer: class QuestSerializer(serializers.ModelSerializer): characters = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Quest fields = "__all__" The problem that I am having is that when I am fetching the list of quests, that it executes a query like this: SELECT ("quests_quest_characters"."quest_id") AS "_prefetch_related_val_quest_id", "characters_character"."id", "characters_character"."legacy_id", "characters_character"."name", "characters_character"."subtitle", "characters_character"."avatar", "characters_character"."avatar_crop", "characters_character"."text", "characters_character"."is_npc", "characters_character"."is_hidden", "characters_character"."dm_notes", "characters_character"."campaign_id", "characters_character"."created_at", "characters_character"."updated_at" FROM "characters_character" INNER JOIN "quests_quest_characters" ON ("characters_character"."id" = "quests_quest_characters"."character_id") WHERE "quests_quest_characters"."quest_id" IN (1281, 1280, 1279, 1278, 1277, 1276, 1275, 1274, 1273, 1272, 1271, 1270, 1269, 1268, 1267, 1266, 1265, 1264, 1263, 1262, 1261, 1260, 1259, 1258, 1257, 1256, 1255, 1254) That is a big query with a lot of fields, even though only an array of character ids is given back in the JSON result, so why is it fetching all this information? It should just fetch this, I would imagine: SELECT "character_id" FROM "quests_quest_characters" WHERE "quest_id" IN (1281, 1280, 1279, 1278, 1277, 1276, 1275, 1274, 1273, 1272, 1271, 1270, 1269, 1268, 1267, 1266, 1265, 1264, 1263, 1262, 1261, 1260, 1259, 1258, 1257, 1256, 1255, 1254) My view: class QuestController(viewsets.ModelViewSet): serializer_class = QuestSerializer … -
Django Backend Image not displaying
I've tried many ways but nothing works. I can't find a solution to this issue. My frontend is React and My backend is Django. On browser only show the URL path link of the image instead of an image. I've tried to add this code to another template and It was working but this one does not work. browser display My settings.py INSTALLED_APPS = ['django.contrib.staticfiles',] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' My urls.py from django.views.generic import TemplateView from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if not settings.DEBUG: urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] My Model looks like this class Product(models.Model): name = models.CharField(max_length=200) image = models.ImageField(blank=True) description = models.TextField() price = models.DecimalField(max_digits=9, decimal_places=2) createdAt = models.DateTimeField(auto_now_add=True) def __str__(self): return f" '{self.name}' " -
Confirmation message after deletion Django
How can I display a success message on a different page after I have deleted someone? The page it redirects to is a page that displays all of the workers. I've also tried displaying it in the current page using timer.sleep(10) to stop the redirect for a while but it seems to ignore that code and instantly redirect the page. Either way is fine with me. I'm using the DeleteView generic display view. views.py class WorkerDelete(SuccessMessageMixin, LoginRequiredMixin, DeleteView): model = Worker context_object_name = 'worker' success_url = reverse_lazy('workers') worker_confirm_delete.html (Template) {% block content %} <a href="{% url 'workers' %}">Go Back</a> <form method="POST"> {% csrf_token %} <p>Are you sure you want to delete this worker? "{{worker}}"</p> <input type="submit" value="Delete"> </form> {% endblock content %} -
can't iterate over multiple zip lists in django template
I'm trying to iterate a zip variable to templates. So I work well with two items but after adding 3 items to zip variable I can't iterate it in for loop like before.Here 'subj' lastest item. zip variable zipped_lists = zip(card_postings, arrays, subj) template {% for card,posts,contents in zipped_lists %} <div class="card"> <div class="card-body"> <h4 class="text-center">{{ card }}</h4> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"> {% for post in posts%} <div class="col"> <div class="card"> <div class="card-header text-center text-primary"> <h5>{{ post }}</h5> </div> <ul class="list-group list-group-flush"> {% for par,gray,aux,verb in contents %} <li class="list-group-item border-0"> <i>{{par}} {{gray.0}} {{aux.0}} {{verb.0}}</i> </li> {% endfor %} </ul> </div> </div> {% endfor %} </div> </div> </div> {% endfor %} By the way I print 'suj' to terminal it also works well. -
Django - Count and filter in queryset
i want to create a complex queryset , after many time witout sucess :( i ask your help, is my models: class Commit(odels.Model): date = models.DateTimeField(auto_now_add=True) created = models.BooleanField(default=False) creator = models.ForeignKey( get_user_model(), on_delete=models.SET_NULL, null=True, blank=True, related_name="%(class)s_creator" ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') uuid = models.CharField(max_length=200) updated_fields = models.TextField(null=True, blank=True) i want to count how many "commit" user have, remove user if user as no "commit" and commit lower than 7 days , sort by upper, and remove my account to this filter , how can to this ? thx -
How to relay user actions from the server to an external device
I have a web interface that allows the user to send remote commands to 1 or 2 robots. Currently the tasks are saved in the database (for logging as well) and the robot(s) keeps polling the django backend using GET requests every 125ms which gives acceptable response time without overly stressing the backend. In short: Action(User) -> [Remote Control UI] -> Django -> DB (based on user input) To get the actions the robot then does a GET request to Django as something like: while(ros::ok()) { response = requests.get(task_url, timeout=5) // input task(s) to state machine // execute task if possible rate.sleep(); } My question is: is there a better way? The remote control is sometimes disabled as the robot goes out of Wi-Fi so the solution needs some degree of flexibility to re-connection, IP changes and connection errors. I though about possible alternatives but not sure they are feasible: Require robots to register and save their IP (?) and send the command to the robot if registered Multicast the command to the entire Wi-Fi subnet (?) and let the robot read it Use django channels or some similar technology? I only found examples with [django or flask] + javascript. … -
Django: ValueError: Cannot assign "<User: x>": "UserRelatinoship.x" must be a "User" instance
I am trying to automatically create a relationship between two test users in a migration in Django. My migration code looks like this: # Generated manually from django.db import migrations, transaction from django.contrib.auth import get_user_model def setup_test(apps, schema_editor): User = get_user_model() User.objects.create_superuser("admin", "admin@gm.org", "123") x = User.objects.create_user( username="x", email="a@gm.org", password="123" ) y = User.objects.create_user( username="y", email="b@gm.org", password="123" ) UserRelatinoship = apps.get_model("myapp", "UserRelatinoship") UserRelatinoship.objects.create(x=x, y=y, active=True) class Migration(migrations.Migration): dependencies = [ ("myapp", "0001_initial"), ("myapp", "0002_manual"), ] operations = [ migrations.RunPython(setup_test), ] The users are created fine, but then when I try to create the relationship I get the error ValueError: Cannot assign "<User: x>": "UserRelatinoship.x" must be a "User" instance.. Note I modified some names from my original code. Any help is greatly appreciated!