Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: numpy.core.multiarray failed to import keeps coming back
I searching informations for my thesis. My goal is to make a website where I can upload pictures and algorithms sort them seperately. Like face, car, etc. I haven't reached this part yet. My current problem is the following: I'm making a simple picture upload in django's admin site where my pictures will be edited by simple algorithms using opencv, like bgr2rgb, bgr2hsv. I used django, matplotlib, opencv-python, and pillow. I made a new environmental for it. I set it up everything and when i run the code python manage.py makemigrations everything worked fine. (I use git for terminal) After I did some coding, and saved it I did run again, but I got some errors: File "C:\Users\Krist▒f\Desktop\Thesis\mywork\lib\site-packages\numpy\__init__.py", line 305, in <module> _win_os_check() File "C:\Users\Krist▒f\Desktop\Thesis\mywork\lib\site-packages\numpy\__init__.py", line 302, in _win_os_check raise RuntimeError(msg.format(__file__)) from None RuntimeError: The current Numpy installation ('C:\\Users\\Krist▒f\\Desktop\\Thesis\\mywork\\lib\\site-packages\\numpy\\__init__.py') fails to pass a sanity check due to a bug in the windows runtime. See this issue for more information: (an url i had to delete) 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\Krist▒f\Desktop\Thesis\mywork\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Krist▒f\Desktop\Thesis\mywork\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\Krist▒f\Desktop\Thesis\mywork\lib\site-packages\django\__init__.py", … -
How to avoid a NonType error in template when using ForeignKey in Model?
I want to access the region of the user in my template: {% if object.seller.profile.post_code %}{{ object.seller.profile.post_code }} {% endif %}{% if object.seller.profile.city%}{{ object.seller.profile.city }}<br/>{% endif %} {% if object.seller.profile.region.name %}{{ object.seller.profile.region.name }}, {% endif %}{% if object.seller.profile.region.country.name %}{{ object.seller.profile.region.country.name }}{% endif %} This is my model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics', verbose_name='Profilbild') post_code = models.CharField(max_length=5, blank=True, verbose_name='Postleitzahl') region = models.ForeignKey(Region, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Region', help_text='Bundesland oder Kanton') city = models.CharField(max_length=50, blank=True, verbose_name='Stadt') street = models.CharField(max_length=50, blank=True, verbose_name='Straße') class Region(models.Model): name = models.CharField(max_length=30, verbose_name='Region', help_text='Bundesland oder Kanton', default='Berlin') symbol = models.CharField(max_length=30, verbose_name='Region-Kürzel', default='BER') country = models.ForeignKey('Country', on_delete=models.CASCADE, null=True, verbose_name='Land', default=0) class Country(models.Model): name = models.CharField(max_length=30, verbose_name='Land', default='Deutschland') symbol = models.CharField(max_length=4, verbose_name='Kürzel', default='DE') But I don't want to force the user to enter their adress data. But if the ForeignKey-Fields are not filled I get 'NoneType' object has no attribute 'country' Is there a more a elegant way than checking each field if it is filled in the views.py and adding it separately to the context? -
Why won't the server.log for my PythonAnywhere server refresh?
The server.log for my PythonAnywhere server is not refershing. The last entries are dated 3 days ago. I've tried refreshing the URL for the server log, looking in the var/log directory, tailing the file, restarting the server, and emptying my browser cache. Is there something else I can try? -
Which is better: fcm-django or django-push-notifications?
I'm developing a DRF API for an angular frontend and have to implement push notifications and so, I came across two libraries: fcm-django and django-push-notifications. I read the README file for both repos to try to understand the differences and choose one. It seems to me that fcm-django is better as it provides a better abstraction (only one model: FCMDevice) for all types of devices. If I were to use django-push-notifications then I would have to make 3 queries, one for each model (GCMDevice, APNSDevice and WNSDevice), to send the same message, which seems to me utterly redundant. However, django-push-notifications appears to be more famous (1.7k stars) so obviously I'm missing something here. The only advantage that I see is that for django-push-notifications I don't need to set up a firebase project if my app is web-only (in which case I would only need WNSDevice model), but still, what if I later decide to develop an android or iOS app? Isn't fcm-django approach more flexible? -
Cannot connect to my site through apache from outside work network
I inherited an apache web server setup with another VM running apache just to act as a firewall. After some digging around I thought I understood how it worked: VM-webfirewall IP = xxx.xx.xx.xxx our outside ip address VM-web-server IP = 10.1.1.72 our inside IP address. Webfirewall seems to run apache and has an /etc/httpd/sites-enabled folder with conf files for each of our internal websites like: weather.abc.com database.abc.com which is all from our www.abc.com now it has two conf files the second one always ending in -ssl.conf So an example of two conf files: flower.conf <VirtualHost *:80> ServerName flower.abc.com ServerAlias flower Redirect "/" "https://flower.abc.com </VirtualHost> then flower-ssl.conf #xxx.xx.xxx.xxx is of course our outside IP address of this machine <VirtualHost xxx.xx.xxx.xxx:443> ServerName flower.abc.com ServerAlias flower ServerAdmin workers@abc.com #DocumentRoot /dev/null LimitRequestLine 200000 <If "%{HTTP_HOST} != 'flower.abc.com'"> Redirect "/" "https://flower.abc.com/" </If> Include extra/ssl-certs ProxyRequests Off ProxyPass / http://thedb.abc.com:8080/ ProxyPassReverse / http://thedb.abc.com:8080/ <Proxy *> AuthType Basic AuthName "Flower Protected Website" AuthBasicProvider file AuthUserFile /etc/httpd/htpasswd Require user flowerdb Order deny,allow Allow from all </Proxy> </VirtualHost> So these work great! The request comes in, it goes off to our flower database and boom right away if you are offsite asks for a user name and password. This … -
Is it possible to keep Django Admin Panel accesible in production mode? (DEBUG=False)
I am developing a webpage for my college where we will show ouur investigations, to solve that i decided to use the admin panel. The problem is that when I deply in production the webage I get a 500 Bad request I have left the deault admin path Also changed the path for admin and still having the same issue -
django-tables2: Displaying a dict
I want to display a list of dicts, that is not coming from a model. The list is produced by calling an external API(GETDATAFROMAPI()). The dict looks like this: [{"name": "testname", "value": 23}, {"name": "test2name": "value": 123}] My views.py looks like this: class Index(SingleTableView): table_class = ProductTable login_url = '/login/' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['table'] = GETDATAFROMAPI() return self.render_to_response(context) any the tables.py: class ProductTable(tables.Table): PName= tables.columns.TemplateColumn(template_code=u"""{{ record.name}}""", orderable=False, verbose_name='productName') class Meta: attrs = {"class": "table table-striped table-hover table-borderless",} fields = ("PName",) sequence = fields empty_text = ("There are no shelves ") -
How to serialize 2 models fields as one form?
I have following serializers: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['profile_pic'] class UserSerializer(serializers.HyperlinkedModelSerializer): userprofile = ProfileSerializer() class Meta: model = User fields = ('id', 'username', 'email', 'password', 'is_superuser','userprofile') extra_kwargs = {'password': {'write_only': True, 'required': True}, 'is_superuser': {'read_only': True, 'required': False}} def create(self, validated_data): user = User.objects.create_user(**validated_data) # UserProfile.objects.create(author = user) # Token.objects.create(user=user) return user And UserProfile model extended from user: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(null=True, blank=True) def __str__(self): return self.name So, currently I get following data: { "id": 11, "username": "Arman1", "email": "bsai@gmail.com", "is_superuser": false, "userprofile": { "profile_pic": null } } But now I want to API in same level with main User like this: { "id": 11, "username": "Arman1", "email": "bsai@gmail.com", "is_superuser": false, "profile_pic": null } Please help me to do this. Thanks in advance! P.S I tried to do the following: def to_representation(self, instance): data = super(UserSerializer, self).to_representation(instance) userprofile = data.pop('userprofile') for key, val in userprofile.items(): data.update({key: val}) return data However, it returns 'NoneType' object has no attribute 'items' -
Django annotated queryset - resulting SQL query duplicates
Let's imagine I have two models: User and Event: class User(models.Model): email = models.EmailField(_('Email'), max_length=255, unique=True, db_index=True) class Event(models.Model): class Type(models.IntegerChoices): ONE = 1, 'One' TWO = 2, 'Two' type = models.PositiveSmallIntegerField('Type', default=Type.ONE, choices=Type.choices, null=False, blank=False) when = models.DateTimeField(_('When?'), blank=True, null=True) Now I have a queryset that is defined like below, to filter on users whose number of events are a multiple of 5. Using the db-side function Mod(). cycle_size = 5 users = User.objects.annotate( event_count=Coalesce(Subquery( Event.objects.filter( user__pk=OuterRef('pk') ).order_by( 'user__pk' ).annotate( count=Count('pk', distinct=True) ).values( 'count' ), output_field=models.IntegerField() ), 0), event_cycle_mod=Mod(F('event_count'), Value(cycle_size )) ).filter( event_count__gt=0, event_cycle_mod=0 ) It works. But The resulting SQL query that is generated looks like the following: SELECT `user`.`id`, FROM `user_user` WHERE ( `user_user`.`id` IN ( SELECT V0.`id` FROM `user_user` V0 WHERE ( COALESCE( ( SELECT COUNT(DISTINCT U0.`id`) AS `count` FROM `event_event` U0 WHERE ( U0.`user_id` = V0.`id` ) GROUP BY U0.`user_id` ORDER BY NULL ), 0 ) > 0 AND MOD( COALESCE( ( SELECT COUNT(DISTINCT U0.`id`) AS `count` FROM `event_event` U0 WHERE ( U0.`user_id` = V0.`id` ) GROUP BY U0.`user_id` ORDER BY NULL ), 0 ), 5 ) = 0.0 ) ) ) The question is the following: is it normal that the whole COALESCE() and … -
TypeError: must be real number, not str : Django
I'm getting this Error: TypeError: must be real number, not str. when i printing the request data lat2, lon2 then it's print float types of number. when i running below code then it's throwing me error that, must be realnumber not str type. It would be great if anybody could help me out to solve this issues. thank you so much in advance. def distance(lon1, lat1, lon2, lat2): lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # Haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * asin(sqrt(a)) r = 6371 # Radius of earth in kilometers return(c * r) # calculate the result class GarageShopDetailAPIView(APIView): def get(self,request,*args,**kwargs): lat2 = self.request.GET.get('lat2', None) lon2 = self.request.GET.get('lon2', None) queryset = ShopOwnerShopDetails.objects.filter(id=query_id) serializer = ShopOwnerShopDetailsSerializer(queryset, many=True, context={'request':request}) data = serializer.data km_difference = [] for record in data: lon1 = record['lon'] lat1 = record['lat'] km_differ = distance(lon1, lat1, lon2 , lat2) km_difference.append({"km_difference":km_differ}) -
how to insert excel file into sql satabase of django and then read that file?
What i want to do is that i want to save an excel file into my db. I am working on python django and db is sql. Currently i have given path of my file to a variable and then reading that file. But i want to save file in database through choose file tag in html. Kindly help me in this regard -
I want to remove new line if present in a string using html django (python)
urls: path('admin/', admin.site.urls), path('',views.index,name='index'), path('analyze',views.analyze,name='analyze'), index.html <form action='/analyze' method='get'> <textarea name='text' style='margin: 0px; width: 721px; height: 93px;'></textarea><br> <input type="checkbox" name="removepunc"> Remove Punctions <br> <input type="checkbox" name="fullcaps"> Uppercaps<br> <input type="checkbox" name="newlineremove"> New line remove<br> <button type="submit">Analyse text</button> analyze.html: <body> <h1>Your analyzed text</h1> <p> <pre>{{analyzed_text}}</pre> </p> views.py: def index(request): return render(request,'index.html') def analyze(request): djtext=request.GET.get('text','default') newlineremove=request.GET.get('newlineremove','off') print(newlineremove) print(djtext) if newlineremove == "on": analyzed="" for char in djtext: if char !="\n": analyzed=analyzed + char else: analyzed=analyzed + " " print(analyzed) params={'analyzed_text':analyzed} return render(request,'analyze.html',params) suppose newlineremove=="on" and input is: dam dam output is(for print in terminal): on dam dam dam but it was supposed to be: on dam dam dam dam but on the web (analyze.html) dam dam -
How to search a queryset by id without additional db calls in Django
Is there a way to search a Django queryset by id or a combination of fields without making additional calls to the database. Would something like this be a single db query? qs = Employee.objects.filter(restaurant='McDonalds') emp1 = qs.filter(id=1) emp2 = qs.filter(id=2) emp3 = qs.filter(id=3) Or is the only way to do something like this to map ids to the model instances beforehand? qs = Employee.objects.filter(restaurant='McDonalds') emp_map = {instance.id: instance for instance in qs} emp1 = emp_map.get(1) emp2 = emp_map.get(2) emp3 = emp_map.get(3) -
Django doesnt registrate my models from addon
I have migrated from Django 1.8 to 2.2 and I cant solve problem with database for few days. I have addon registrated in INSTALLED_APPS, then I have folder of my addon with apps.py,models.py and logic.py. Registration in INSTALLED_APPS: INSTALLED_APPS = [ ..., 'myapp.addons.pcpanalysis' ] Also tried 'myapp.addons.pcpanalysis.apps.PcpConfig'. My apps.py: from __future__ import absolute_import from django.apps import AppConfig class PcpConfig(AppConfig): name = "myapp.addons.pcpanalysis" def ready(self): from myapp.addons.pcpanalysis import logic logic.register_events() My handler of event in logic.py is working properly, but when event occur, I get this error: (1146, "Table 'project.myapp.addons.pcpanalysis_node' doesn't exist") I've tried to look into container with database and there are missing only models from my addon, all other models are in DB. I've tried to change names, check everything but seems that has no effect. I also don`t understand that my handler in logic.py and registration in apps.py works properly and there is problem only with models. I will be happy for all tips that I can try. Thank you! P.S. Everything was working properly in Django 1.8, migration to 2.2 changed it. I hadn't changed any settings variables before it occured. -
Can i deserialize a fk object using just the name field?
I have two models - one is a foreign key of the other, I have serializers for each. What I'm trying to accomplish is a way to serialize/deserialize using only the name of the foreign key field, rather than a nested object. The fk field in question is TableAction. My question is how do I define my serializer in order to accomplish this. I think maybe specifically I just need to know which serializer methods to override in order to drop that logic into. When I send a payload, I do not want to send a nested TableAction object, instead I just wanted to send the name of the TableAction. Due to business requirements I cannot change the structure of the payload being sent. models class TableEntry(models.Model): reward_table = models.ForeignKey( RewardTable, related_name="entries", on_delete=models.CASCADE ) action = models.ForeignKey( TableAction, max_length=100, related_name="entries", on_delete=models.CASCADE ) reward_item = models.ForeignKey( RewardItem, related_name="reward_table_entries", on_delete=models.CASCADE ) reward_item_amount = models.PositiveIntegerField() class Meta: unique_together = ("reward_table", "reward_item", "action") class TableActionManager(models.Manager): def get_by_natural_key(self, name, application): return self.get( name=name, application=application ) class TableAction(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) application = models.ForeignKey( Application, related_name="reward_actions", on_delete=models.CASCADE ) objects = TableActionManager() class Meta: unique_together = ("application", "name") def __str__(self): return self.name def natural_key(self): … -
django-datatable-view without a model
I wanted to switch from django-tables2 to a more JS driven table system. My django app however does not have it's own database, but runs on a variety of functions that provide a big number of dicts/json. I wanted to populate my table with data from a dict/json, not from a model - is there a way to do this? -
Not Found: /nurse/articles/10/ Django Rest Framework
I have started learning Django rest Framework.I read an article and tried on my computer.But unable to figure out why am i getting this error. Some one please help me.Thank you models.py class Author(models.Model): name = models.CharField(max_length=255,blank=True,null=True) email = models.EmailField() def __str__(self): return str(self.name) class Article(models.Model): title = models.CharField(max_length=120,blank=True,null=True) description = models.TextField(blank=True,null=True) body = models.TextField(blank=True,null=True) author = models.ForeignKey('Author', on_delete=models.CASCADE,related_name='articles') def __str__(self): return str(self.title) views.py class ArticleView(APIView): def get(self, request,pk=None): try: if pk: allowance=get_object_or_404(Article.objects.all(),pk=pk) print(allowance) serializer = ArticleSerializer(allowance,many=True) return Response({serializer.data}) else: articles = Article.objects.all() serializer = ArticleSerializer(articles, many=True) return Response({"articles": serializer.data}) except Exception as e: print(e) return Response({"success":False,"message":str(e)},status=status.HTTP_400_BAD_REQUEST) def post(self, request): try: article = request.data.get('article') print('Data',article) # Create an article from the above data serializer = ArticleSerializer(data=article) if serializer.is_valid(raise_exception=True): article_saved = serializer.save() return Response({"success": "Article '{}' created successfully".format(article_saved.title)}) except Exception as e: print(e) return Response({"success":False,"message":str(e)},status=status.HTTP_400_BAD_REQUEST) def put(self, request, pk): saved_article = get_object_or_404(Article.objects.all(), pk=pk) data = request.data.get('article') serializer = ArticleSerializer(instance=saved_article, data=data, partial=True) if serializer.is_valid(raise_exception=True): article_saved = serializer.save() return Response({"success": "Article '{}' updated successfully".format(article_saved.title)}) def delete(self, request, pk): # Get object with this pk article = get_object_or_404(Article.objects.all(), pk=pk) article.delete() return Response({"message": "Article with id `{}` has been deleted.".format(pk)},status=204) serializers.py class ArticleSerializer(serializers.Serializer): # class Meta: # model = Article # fields = ('title', 'description', … -
Choosing the database for my Django Project
I'm working on a Django Project for the very first time, also I'm new to programming so I really don't know that much, I'm learning through videos. I'm trying to develop a project management system for a web agency. (That maybe in future will also manage client and their informations and will give the possibility of making invoices). I know that stack overflow is used to make specific and technical question. But I tried to research the things I've doubts on but since I'm new to programming often the answers aren't really clear to me. So I hope you'll accept these post because really I don't know where else to look. I have some questions: How do I make a Django Project secure? Like do I need to be a really skilled programmer to block for example hackers from trying to access to my web app? How do I make sending email through my web app secure? or payments? or the file imported/exported from its users? Some functionalities on some view (like the button to add a new project) should only be available for some type of users, what is the best way of giving users permission? is it using … -
How to save multiple selected data using React Apollo client?
Recently I have started to learn react with Django and GraphQL and I face some problem. I want to create an event member form where I will input event name, description & location and I want to select multiple User and save this event for every user separately. models.py class EventMember(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) event = models.ForeignKey(Event,related_name='events', on_delete=models.CASCADE) create_event_member.js const CreateEventMember = ({classes}) =>{ const [open, setOpen] = useState(false) const [name,setName] = useState("") const [description,setDescription] = useState("") const [locationId,setLocationId] = useState("") const [userId,setUserId] = useState([""]) const handleSubmit = (event,createEventMultipleUsers) =>{ event.preventDefault() createEventMultipleUsers() } return ( <> {/* Create Event Button */} <Button onClick={()=>setOpen(true)} variant="contained" color="secondary"> Add Event Member </Button> <Mutation mutation={CREATE_EVENT_Member} variables={{ name,description,locationId,userId}} onCompleted={ data =>{ console.log({data}); setOpen(false); setName(""); setDescription(""); setLocationId(""); setUserId([""]); }} refetchQueries={() =>[{ query : GET_QUERY }]} > {( createEventMultipleUsers, {loading,error}) =>{ if (error) return <div>Error</div> return( <Dialog open={open} className={classes.dialog}> {/* <listLocation></listLocation> */} <form onSubmit={event=> handleSubmit(event,createEventMultipleUsers)}> <br></br> <DialogTitle>Create Event Member</DialogTitle> <DialogContent> <DialogContentText> Add a event title, Description, location and Users </DialogContentText> <FormControl fullWidth> <TextField label = "name" placeholder="Enter a title for this event" className={classes.textField} onChange={event=>setName(event.target.value)} /> </FormControl> <FormControl fullWidth> <TextField multiline rows="4" label = "Description" placeholder="Enter Description" className={classes.textField} onChange={event=>setDescription(event.target.value)} /> </FormControl> <FormControl fullWidth> <InputLabel htmlFor="grouped-native-select"></InputLabel> <Select native defaultValue="" … -
Serving static files from S3 bucket not working?
I have configured an S3 bucket to store and serve static and media files for a Django website, currently just trying to get the static files needed for the admin pages and all that. Here is all the static and AWS config info in my settings file: STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'config.storage_backends.MediaStorage' #used to authenticate with S3 AWS_ACCESS_KEY_ID = 'AKIAWWJOJKZGFSJO2UPW' #not real one AWS_SECRET_ACCESS_KEY = 'KNg1z5wXWiDRAIh4zLiHgbD2N3wtWZTK' #not real one #for endpoints to send or retrieve files AWS_STORAGE_BUCKET_NAME = 'my-static' #not real bucket name AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400',} AWS_LOCATION = 'static' STATIC_ROOT = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'config/static'), ] Of course I replaced any sensitive variables with fake ones for the purpose of this post. I have gone through many tutorials and other posts and I seem to have my STATIC_URL configured correctly but whenever I runserver and go to the admin pages, none of the css is applied. I do not think it is properly retrieving the static files (they are all uploaded to the S3 bucket) from the bucket, but I am stuck on what to do. -
Find if static file exists before calling in deployment - Django
In production I am able to run: #views.py from django.contrib.staticfiles import finders result = finders.find(f'Images/{var}') context = {"r", results} #template.html {% if r %} {% with 'Images/'|add:var as var %} <img src="{% static var %}"> {% endwith %} {% endif %} However, now that my files are being stored in Google's buckets finders.find(f'Images/{var}') keeps returning False and my images aren't being displayed. I need a way to test if files exists prior to calling them to avoid displaying empty boxes when a variable's image does not exist. Any help would be much appreciated, thank you! -
django.db.utils.IntegrityError: UNIQUE constraint failed: authentication_user.email
I am trying create user through an API, But i am struck on above error. Below are the code of the User and its manager. Here, I am creating custom user model. class UserManager(BaseUserManager): def create_user(self,username,email, password=None): if username is None: raise TypeError('Users should have a Username') if email is None: raise TypeError('Users should have a Email') user = self.model(username=username,email=self.normalize_email) user.set_password(password) user.save() return user def create_superuser(self,username,email, password=None): if password is None: raise TypeError('Password should not be none') user = self.create_user(username, email, password) user.save() return user class User(AbstractBaseUser,PermissionsMixin): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255,unique=True,db_index=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects= UserManager() def __str__(self): return self.email Below is serializers.py file. class RegisterSerializers(serializers.ModelSerializer): password = serializers.CharField(max_length=68, min_length=6, write_only=True) class Meta: model = User fields = ['email','username','password'] def validate(self, attrs): email = attrs.get('email','') username = attrs.get('username','') if not username.isalnum(): raise serializers.ValidationError('The username should only contain alphanumeric character') return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) Here is POST request in views.py class RegisterView(generics.GenericAPIView): serializer_class = RegisterSerializers def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data return Response(user_data,status=status.HTTP_201_CREATED) I am new to drf. Kindly help me out, thanks. -
Wildcard exclusion of template path for makemessages
I'm writing a management command to automate the ignore paths sent to django's makemessages command. The reason for this is that the project has a directory of themes (html files) and a given theme may only be supported by 1 language. Therefore I want to ignore certain paths for some locales. For example, theme A might be for Japan, and theme B might be for Italy. So ideally I want a management command that does this; class Command(BaseCommand): help = ( "Checks the provided locale to automatically provide the ignored " "paths allowing us to only add certain templates to the po " "files.\n\n" "Django's standard `makemessages` is then called with that ignored " "pattern and the provided locale" ) ignored = { 'ja': [ 'project/templates/themes/b/**/*.html', ], 'it': [ 'project/templates/themes/a/**/*.html', ] } def add_arguments(self, parser): parser.add_argument( '--locale', '-l', default=[], action='append', help='Creates or updates the message files for the given ' 'locale(s) (e.g. pt_BR). ' 'Can be used multiple times.', ) def handle(self, *args, **options): """ Run the command """ locale = options['locale'] locales = set(locale) for code in locales: message_kwargs = { 'locale': [code, ], 'ignore': self.ignored[code] } call_command("makemessages", **message_kwargs) However this doesn't exclude the templates, only if I include … -
Running Python Tests from Subpackages
I've got a package - we'll be creative and call it package - and in there are api and dashboard packages, each with a tests module and various files filled with tests. I'm using Django test runner and rather than having package.api.tests and package.dashboard.tests in my run configs, I'd like to just have package.tests and have that run all the tests in the packages below it. I added a tests package to package and in the init tried a few things like from package.api.tests import * or using an all declaration but that didn't work. Is there a way to make this happen? It's not the most annoying thing in the world, but it's a package that gets brought in to each project we do, and it would just be a bit simpler to have instructions of "Run package.tests", especially if we end up adding more packages beyond api and dashboard. -
Django Formset Not Validating Even When Fields Are Filled
I am working with a formset in django and I am having lots of difficulty getting it to post properly. I am simply receiving an error that not there is not HTTP response, which I understand is happening because I have not provided one when the form is not valid, but my main concern is why is my form not valid when I am in fact filling out the only required field. Below is the code I am working with. It is the TaskGroupDetailForm which is failing to validate: models.py class TaskType(models.Model): name = models.CharField(max_length=100, null=False, blank=False, unique=True) description = models.CharField(max_length=500, null=False, blank=False) def __str__(self): return self.name class TaskGroup(models.Model): name = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.name class TaskGroupDetail(models.Model): taskGroup = models.ForeignKey(TaskGroup, null=True, blank=True) taskType = models.ForeignKey(TaskType, null=False, blank=False, on_delete=models.CASCADE) forms.py class CreateTaskGroupForm(forms.ModelForm): class Meta: model = TaskGroup fields = ['name'] class TaskGroupDetailForm(forms.ModelForm): class Meta: model = TaskGroupDetail fields = ['taskType'] #I am assigning the other field, taskGroup, manually in the view views.py def TaskGroupView(request): detailform = modelformset_factory(TaskGroupDetail, TaskGroupDetailForm, can_delete = False) if request.method == "POST": groupform = CreateTaskGroupForm(request.POST) formset = TaskGroupDetailForm(request.POST) print(formset) if groupform.is_valid(): print(formset.errors) if formset.is_valid(): group = groupform.save() details = formset.save(commit=True) for item in details: item.taskGroup …