Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Mysql Error 1045(28000) access denied for user ODBC@localhost
I know there are a lot of questions concerning the Access denied error for Django, but none of them is helping. What is the configuration: Windows Server 2012 MySQL 5.7 Django with anaconda I am doing basically the tutorial and I have changed the settings.py to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysite', 'User': 'User4711', 'Password': 'xxxx', 'Host': 'localhost', 'Port': '3306', } } I have tried: Creating a database, creating a user root or ODBC and granting all privileges + flushing them and restarting MySQL starting mysql with options -uroot -pXXXX works fine but no chance to do sth with Django on the DB Executing python manage.py makemigrations polls I got the error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module execute_from_command_line(sys.argv) File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\base.py", line 327, in execute self.check() File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\commands\migrate.py", line 61, in _run_checksissues = run_checks(tags=[Tags.database]) File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- … -
Select one record from related table if exists, else return None
I have this two models: class Box(models.Model): class BoxImages(models.Model): box=models.ForeignKey(Box) img=models.ImageField() cover=models.IntegerField(default=0) Only one image can be a cover image for a box and a box might not have any images at all. What I want now is to get list of boxes along with their cover image. But django uses inner join and brings boxes that have corresponding cover images only. Box.objects.filter(box_boximages__cover=1).values('id','box_label') How do I force it to go with left join or left outer join since i read the ORM decides on its own which join to use? -
Using a Django profile field to restrict queryset of a list view
I want to use a field in the Profile model of a logged in user to restrict the queryset used in a Django class based view. My models are: # User profile info class Profile(models.Model): # Relationship Fields user = models.OneToOneField(User, on_delete=models.CASCADE) school = models.ForeignKey('eduly.School', default=1) notes = models.TextField(max_length=500, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() and class School(models.Model): # Fields name = models.CharField(max_length=255) address = models.TextField(max_length=500, blank=True) email = models.CharField(max_length=30) phone = models.CharField(max_length=15) contactName = models.CharField(max_length=30) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.slug def __str__(self): return self.name def get_absolute_url(self): return reverse('eduly_school_detail', args=(self.slug,)) def get_update_url(self): return reverse('eduly_school_update', args=(self.slug,)) class Teacher(models.Model): SCHOOL_ADMIN = 0 CLASS_ADMIN = 1 TASK_ADMIN = 2 ROLES = { (SCHOOL_ADMIN, "School administrator"), (CLASS_ADMIN, "Class administrator"), (TASK_ADMIN, "Task administrator") } # Fields name = models.CharField(max_length=255) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) email = models.CharField(max_length=30) roles = models.IntegerField("Role", choices=ROLES, default=1) # Relationship Fields school = models.ForeignKey('eduly.School', ) class Meta: ordering = ('-created',) def __str__(self): return self.name def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('eduly_teacher_detail', … -
Attribute error when sharing Django page to Facebook
I have a share button in my application to Facebook wall. Everything was working fine yesterday. But when I try to share those pages today the title and the description is showing Attribute error. Even though it is showing like that I could share the page to my Facebook wall and could access the page from Facebook. This issue is showing only for few links. When I debug the url I couldn't find any issue and there is nothing complex in the page. I am attaching the image of the error here. -
I need to display summary report in Django admin site. How do I count number of users where gender status is 0 or 1
I am overriding change_list.html and here is what I have in my admin.py file. def changelist_view(self, request, extra_context=None): response = super().changelist_view(request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'male': Count('gender', gender=1), 'female': Count('gender', gender=0), 'total_helpers': Count('id') } response.context_data['helper'] = list( qs.values('gender').annotate(**metrics).order_by('-male') ) return response In my metrics dictionary, i need a way to count where gender is either 0 or 1. -
How to retrieve/access variable from HTML/Javascript in django views to process it?
I am saving the coordinate(generated by click on google map) in the variable "ccc". Now I want to process this variable in Django. How to get its value like we get from HTML input element (for eg. myX = request.POST.get("myInput")) Here is the curtailed code:- <html> <script> google.maps.event.addListener(map, 'click', function(e) { var ccc = e.latLng.lat(); //I want to retreive this variable //ccc = 77.6746784 }); </script> </html> -
Django custom queryset and export
I have a custom django queryset class, which I use together with custom manager to easly filter objects with chaining. I wanted to add custom method to this class to save its result as a file. However, I am not sure if I am doing it right. How can I get list of objects inside as_file method? class EntryQuerySet(models.QuerySet): def as_file(self, filename='export.xls'): # data = ??? how can I get results here??? print('exporting as {}'.format(filename)) def active(self): return self.filter(status__in=[1, 4, 5]) def with_email(self): return self.filter(contact__email__isnull=False) def by_city(self, city): return self.filter(address__city__icontains=city) def in_next_days(self, days=7): now = datetime.datetime.today() delta = now + relativedelta.relativedelta(days=days) return self.filter(start_date__gte=now, start_date__lte=delta) def in_last_days(self, days=7): now = datetime.datetime.today() delta = now - relativedelta.relativedelta(days=days) return self.filter(start_date__gte=delta, start_date__lte=now) class EntryManager(models.Manager): def get_queryset(self): return EntryQuerySet(self.model, using=self._db) def active(self): return self.get_queryset().active() def by_city(self, city): return self.get_queryset().by_city(city) def with_email(self): return self.get_queryset().with_email() def in_next_days(self, days): return self.get_queryset().in_next_days(days) def in_last_days(self, days): return self.get_queryset().in_last_days(days) I use this as follows: entries = Entry.objects.active().by_city('My city').in_next_days(5) And I want something like: entries = Entry.objects.active().by_city('My city').in_next_days(5).as_file('myfilename.xls') How can I achieve this? -
Django application not responding while running with gunicorn and wsgi
I have developed a django application and it is running fine with the manage.py, but when I am running it with below command gunicorn project_name.wsgi:application Aplication started fine with link localhost:8000 but when clicking on next process in application it is getting stuck i.e not responding just keep waiting for next page. the log output is [2017-11-10 16:07:19 +0530] [2080] [INFO] Starting gunicorn 19.6.0 [2017-11-10 16:07:19 +0530] [2080] [INFO] Listening at: http://127.0.0.1:8000 (2080) [2017-11-10 16:07:19 +0530] [2080] [INFO] Using worker: sync [2017-11-10 16:07:19 +0530] [2087] [INFO] Booting worker with pid: 2087 [<project_name: project_name object>] [<project_name: project_name object>] destination_path /home/ravi/lqiDemo/project_name/media/data/2017/11/8/13/64001859 [2017-11-10 16:07:54 +0530] [2080] [CRITICAL] WORKER TIMEOUT (pid:2087) [2017-11-10 10:37:54 +0000] [2087] [INFO] Worker exiting (pid: 2087) [2017-11-10 16:07:54 +0530] [2128] [INFO] Booting worker with pid: 2128 [2017-11-10 16:08:26 +0530] [2080] [CRITICAL] WORKER TIMEOUT (pid:2128) [2017-11-10 10:38:26 +0000] [2128] [INFO] Worker exiting (pid: 2128) [2017-11-10 16:08:26 +0530] [2135] [INFO] Booting worker with pid: 2135 [2017-11-10 16:08:57 +0530] [2080] [CRITICAL] WORKER TIMEOUT (pid:2135) [2017-11-10 10:38:57 +0000] [2135] [INFO] Worker exiting (pid: 2135) [2017-11-10 16:08:57 +0530] [2152] [INFO] Booting worker with pid: 2152 my wsgi file is: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings") application = get_wsgi_application() Is there any solution of … -
Why are my mocked properties not returning the specified value but a MagicMock object and my mocked method is returning the expected value?
I am having trouble getting my test to run as expected. I am trying to mock the return value for two properties and a method for one test but instead of getting the desired return value I get a MagicMock object. I can not figure out how to do this. The thing that irritates me the most is that mocking the method works as expected but for the two properties it does not. Is this a problem I am having because I am using properties or because of the foreignkey relationships or am I doing something basic wrong? I am using Django 1.8, Python2.7, model-mommy, unittests, mock Here are some snippets of my code, I hope they are sufficient to understand the situation: App1 called producers # In producers.models.Producer: @property def is_valid(self): # do stuff return True App2 called customers # In customers.models.Customer: @property def is_valid(self): # do stuff return True def is_allowed_to_purchase_from_producer(producer): # do stuff return True App3 called purchases # In purchases.models class Purchase(BaseModel): producer = ForeignKey('Producers.Producer', related_name="purchase") customer = ForeignKey('Customers.Customer', related_name="purchase") def clean(self): if not self.producer.is_valid: rasie ValidationError if not self.customer.is_valid: raise ValidationError if not self.customer.is_allowed_to_purchase_from_producer(self.producer): raise ValidationError A test for the clean method of the Purchase … -
Bulk create duplicate model plus objects linked by foreign keys linked to that model
I have two database models, let's call them: class People(models.Model): current_job = models.ForeignKey(Job, blank=True) class Job(models.Model): job_title = models.CharField(max_length=512, blank=False) So a People object can have a job which is stored in a separate table and linked via a foreign key. Now I need to duplicate large sections of this table based on a group of people (let's say all people under 40). All properties are same except they're new objects - links should persist between these two new duplicated objects (new_person-new_job should reflect original_person-original_job link). The tables are large; this query results in 1 million objects of people and 400k jobs linked as foreign keys, so I want to bulk create this because doing this in a for loop (for each person, get their job, mint new person, mint new job) takes forever. Is there a smart way of bulk creating these two query sets together such that the foreign key relation persists for the copied items? Any help is appreciated, been driving me nuts last few days! -
Duplicate rows in CSV file Django
In my CSV file duplicate record show. i don't want duplicate record in CSV file. if filtered_record: for row in filtered_record: #print row writer.writerow(row) file_name = 'reports/invoice_reports/' + timezone.now().strftime('%Y_%m_%d_%H_%M_%S.csv') file_path = os.path.join(BASE_DIR, 'static/' + file_name) with open(file_path, 'wb') as f: f.write(response.content) -
While trying to post mptt model via django rest framework getting ValueError: Cannot use None as a query value
Here is the view I'm trying to write tests for: class RestaurantsTreeView(generics.ListCreateAPIView): serializer_class = RestarauntsTreeSerializer def get_serializer_class(self): from rest_framework import serializers if self.request.method == 'GET': return RestarauntsTreeSerializer parent_choices = self.request.user.restaurants_set.filter(status=Restaurants.VISIBLE) class NestedRestaurantDetailSerializer(serializers.ModelSerializer): parent_id = serializers.RelatedField(queryset=parent_choices, allow_null=True, required=False) class Meta: model = Restaurants fields = ("id", "name", "parent_id") return NestedRestaurantDetailSerializer Here is the model I'm trying to create via POST request: from mptt.models import MPTTModel, TreeForeignKey class Restaurants(MPTTModel): name = models.CharField(max_length=255, blank=True, null=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name And finally my test: class CreateRestaurantTestCase(TestCase): def setUp(self): self.user = UserFactory.create() self.user.user_permissions.add(Permission.objects.get(codename='add_restaurants')) self.client = APIClient() self.client.force_authenticate(user=self.user) def test_authorization_required(self): response = self.client.post(reverse('api_v1:restaurants_list'), data={ "parent_id": None, "name": "fake restaurant", }) self.assertEqual(response.status_code, 401) that returns that error: Error Traceback (most recent call last): File "project/cafe/tests/api/test_restaurants.py", line 26, in test_required_fields response = self.client.post(reverse('api_v1:restaurants_list'), data={}) File "env/lib/python3.5/site-packages/rest_framework/test.py", line 299, in post path, data=data, format=format, content_type=content_type, **extra) File "env/lib/python3.5/site-packages/rest_framework/test.py", line 212, in post return self.generic('POST', path, data, content_type, **extra) File "env/lib/python3.5/site-packages/rest_framework/test.py", line 237, in generic method, path, data, content_type, secure, **extra) File "env/lib/python3.5/site-packages/django/test/client.py", line 416, in generic return self.request(**r) File "env/lib/python3.5/site-packages/rest_framework/test.py", line 288, in request return super(APIClient, self).request(**kwargs) File "env/lib/python3.5/site-packages/rest_framework/test.py", line 240, in request request = super(APIRequestFactory, self).request(**kwargs) … -
Chrome automatically refresh page after XMLHttpRequest
I have some strange problem with Google Chrome. I build a search field for my website. Therefor i have implemented some JS to get and process the results (see below). The problem is, when I first enter the page with chrome and using the search with "Enter-key", chrome does the following (request from my server): [10/Nov/2017 10:00:56] "GET /app/student/home/ HTTP/1.1" 200 7372 (entering the page) [10/Nov/2017 10:00:59] "GET /api/searchCourse/daf/ HTTP/1.1" 200 95 (search request) [10/Nov/2017 10:00:59] "GET /app/student/home/? HTTP/1.1" 200 737 (reloading -but why?? ) One Firefox (also with "Enterkey") or Chrome using the "Search-button" it looks different, like that. [10/Nov/2017 10:00:59] "GET /api/searchCourse/daf/ HTTP/1.1" 200 95 (entering the page) [10/Nov/2017 10:00:59] "GET /app/student/home/? HTTP/1.1" 200 737 (search request) I also tried debugging this Problem with Chrome, but than it behaves like it should. Also I have to add, this happens only when I first enter the page after login. When I refresh the page it works good. Can some explain this behavior? My JS-Code: var btnSearch = document.querySelector('.search').addEventListener('click', searchCourse); var txtFieldSearch = document.getElementById('searchField').addEventListener('keydown', function (e) { var key = e.which || e.keyCode; if (key === 13) { searchCourse(); } }); function searchCourse() { document.querySelector('.my-node').style.display = 'none'; var input = … -
Django rest framework filtering by dateTime
I'm trying to filter by dateTime in django restFramework. it seems that it does not work, because it does not filter, it always brings the same results. Model.py #Modelo Fechas que formara parte del modelo horario class Fecha(models.Model): fecha_inicio = models.DateTimeField(blank=True, default='') fecha_fin = models.DateTimeField(blank=True, default='') def __str__(self): return self.fecha_inicio, self.fecha_fin #Modelo Horario class Horario(models.Model): profesional = models.ForeignKey(Profesional, unique=True) fechas = models.ManyToManyField(Fecha) def __str__(self): return self.profesional.user.username View.py class FechaList(generics.ListAPIView): serializer_class = HorarioSerializer queryset = Horario.objects.all() filter_class = HorarioFilter Urls.py url(r'^horario/$', views.FechaList.as_view()) Filters.py class HorarioFilter(django_filters.FilterSet): date_start = django_filters.DateTimeFilter(name="fecha_inicio", lookup_type="gte") class Meta: model = Horario fields = ['date_start'] Thank you!!!! :) -
What to return to django admin if user has not username or something else
In short i am doing online store and in django admin i display authenticated users 'username' but there not authenticated users. So if authenticated users will order something it's okay i have their data. But if unauthenticated users will order? What to show in django admin? If i will request from user only his name from this no result. Because we know django need full authorization models.py class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) products = models.ManyToManyField(Product, through=CartProduct) class Meta: verbose_name = 'Cart' verbose_name_plural = 'Cart' def __str__(self): return self.user.username # That for authenticated users views.py class CartView(View): def get(self,request,*args,**kwargs): cart_id = request.session.get('cart_id') if cart_id == None: cart = Cart() cart.save() request.session['cart_id'] = cart_id cart = Cart.objects.get(id=cart_id) product_id = request.GET.get('product') delete_product = request.GET.get('delete') if product_id: product_instance = get_object_or_404(Product, id=product_id) amount = request.GET.get('amount') cart_product = CartProduct.objects.get_or_create(cart=cart, product=product_instance)[0] if delete_product: cart_product.delete() else: cart_product.amount = amount cart_product.save() return HttpResponseRedirect('/') -
@monthly cron job is not reliable
Our customer wants us to create a report every month. In the past we used a @monthly cron job for this task. But this is not reliable: The server could be down in this minute. Cron does not re-run those jobs If the server is up, the database could be unreachable in this moment. If the server is up and DB is up, there could be a third party system which is not reachable There could be software bug. What can I do, to be sure that the report gets created monthly? It is a django base web application -
I return Response with `status=HTTP_404_NOT_FOUND` but find the 201
In the views.py, I return Response with status=HTTP_404_NOT_FOUND: class CloudServerCreateAPIView(CreateAPIView): serializer_class = CloudServerCreateSerializer permission_classes = [] queryset = CloudServer.objects.all() def perform_create(self, serializer): return Response(data="There is no data left.", status=HTTP_404_NOT_FOUND, exception=Exception()) serializer.save() But when I request the API, I get HTTP 201 Created, not the 404: POST /api/user_productmanage/cloudserver/create/ HTTP 201 Created Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "expiration_time": "2017-12-11T11:11:11+08:00", "profile": "asdas", "buytime": 1, "availablearea": 2 } -
Celery beat process allocating large amount of memory at startup
I operate a Django 1.9 website on Heroku, with Celery 3.1.23. RabbitMQ is used as a broker. After restarting the beat worker, the memory usage is always around 497Mb. This results in frequent Error R14 (Memory quota exceeded) as it quickly reaches the 512Mb limit. How can I analyze what is in the memory at startup? I.e. how can I get a detail of what is in the memory when restarted? Here is a detail of memory consumption obtained with the beta Heroku log-runtime-metrics: heroku/beat.1: source=beat.1 dyno=heroku.52346831.1ea92181-ab6d-461c-90fa-61fa8fef2c18 sample#memory_total=497.66MB sample#memory_rss=443.91MB sample#memory_cache=20.43MB sample#memory_swap=33.33MB sample#memory_pgpgin=282965pages sample#memory_pgpgout=164606pages sample#memory_quota=512.00MB -
When I execute “python manage.py runserver",the following error occurs。Even a new project。
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03DB6540> Traceback (most recent call last): File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 149, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 164, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 74, in __init__ super(WSGIServer, self).__init__(*args, **kwargs) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 453, in __init__ self.server_bind() File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\http\server.py", line 138, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte -
django: UnboundLocalError local variable referenced before assignment
I'm trying to make a social web app with django. I made a form that a user can use to answer a question. Everything worked fine but when I submit form without any content (empty form), I got an error (Unbound Local error "local variable 'new_answer' referenced before assignment". I'm new to django and I don't know much about this so any help will be very kind. here is my view code: def question_detail(request, pk): question=get_object_or_404(Question, pk=pk) #list of active answers for this question answers = question.answers.filter(active=True) answer_form = AnswerForm() if request.method=='POST': #a comment was posted answer_form = AnswerForm(data=request.POST or None) if answer_form.is_valid(): new_answer= answer_form.save(commit=False) new_answer.question = question u=request.user new_answer.name = u new_answer.save() else: answer_form = AnswerForm() new_answer = False question_tags_ids = question.tags.values_list('id', flat=True) similar_questions = Question.objects.filter(tags__in = question_tags_ids)\ .exclude(id=question.id) similar_questions = similar_questions.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-created')[:4] return render(request,'dashboard/post/detail.html', {'question':question, 'answer_form':answer_form, 'new_answer': new_answer, 'similar_questions':similar_questions}) -
Django how to build my query?
I have a form where there is an HTML tag <select> and 2 <option> : True or False. In my view, I built a simple query according to the value returned., for exemple for in the case of returning True : Test = Relation.objects.filter(field=True) It's working fine for True or False because this is a boolean field in my model. Now I would like to make a new <option> to filter True and False, to return all results. Off course I could make : Test = Relation.objects.all() But for a technical reason and because it's just a simple exemple here, I'm looking for a synthax like : Test = Relation.objects.filter(field=*) or : Test = Relation.objects.filter(field=all) This kind of synthax does exist ? Thank you -
How to save objects in django directly to data base?
I'm using django 1.11 python 3.5 and postgresql on ubuntu 16. I'm trying to build something like sports event website. It's consist of 2 parts: Django app. Python script that inserting new objects to django database with events. Code for inserting: get information about max primary key, pk = z INSERT INTO events_event VALUES pk = z, event_name = name .... In this part, everything works correctly. But, when I trying to save objects from django admin, I see an error: IntegrityError at /admin/events/event/add/ duplicate key value violates unique constraint "events_event_pkey" DETAIL: Key (id)=(7) already exists. What is an issue with this problem? How should I organize my code so I can save a lot of objects to a database? -
Django- URLs Regex UUID & Phone numbers
How to support both uuid and phone numbers having +- signs in Django URLs? Currently, for uuid, I've url(r'^(?P<uuid>[0-9A-Fa-f-]+)/$', view_name.as_view()), And for phone number, url(r'^(?P<msisdn>[0-9A-Fa-f-]+)/$', view_name.as_view()), How to have a regex supporting both uuid and phone numbers? PS:- One option is to support every character (.*), but that's a bad practise. -
Django - Deserializing JSONField in DRF
I've a JSONField in model, lets say x. I'm using DRF to save the model instance. Serializer:- class ABCSerializer(serializers.ModelSerializer): class Meta: model = ABC fields = ('x', ) def create(self, data): instance = ABC.objects.create(**data) instance.x = {'key': 'value'} instance.save() When I POST the data, the response returned by creating the object is correctly deserialized, ie { 'id': 1, 'x': { 'key': 'value' } } However, when I GET the data using the id, it return x as str, ie { 'id': 1, 'x': "{\"key\": \"value\"}" } How can I properly deserialize the data back to json? -
Django unable to create instance
so I am trying to problematically create instances but I keep getting this error. The error occurs on the last line rec.save() while I try to makemigrations. It works fine without rec.save() line. I have tried Users.objects.create_user(username="xy",password="password123") and also flushing the database having taken out the rec.save() line. django.db.utils.IntegrityError: NOT NULL constraint failed: catalog_company.modif ied_by_id here is my code from django.db import models from django.contrib.auth.models import User, UserManager from datetime import date import datetime from django.urls import reverse #Used to generate URLs by reversing the URL patterns from django.core.validators import MaxLengthValidator from simple_history.models import HistoricalRecords from simple_history import register register(User, inherit=True) class Company(models.Model): """ Model representing a company invested in. """ name = models.CharField(max_length=200) #details group=models.CharField(max_length=15, default='EQD') stake = models.CharField(max_length=50, blank=True) partners = models.CharField(max_length=50, blank=True) #user details modified_by = models.ForeignKey(User,related_name='Project_modified_by') modified_date = models.DateTimeField(auto_now=True) #to keep records history = HistoricalRecords(inherit=True) def __str__(self): """ String for representing the Model object. """ return self.name def get_form_url(self): """ Returns the url to access the form to change model attributes. """ return reverse('forms', args=[str(self.id)]) def attrsetter(self,attr,value): """ set attribute of an instance """ return setattr(self, attr, value) @property def _history_user(self): #to track who modified return self.modified_by @_history_user.setter #to track what was modified def _history_user(self, value): …