Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: int() argument must be a string, a bytes-like object or a number, not 'Games'
I have a model named Games with some fields, I'm trying to query 2 latest games & 2 random games from the database. Here's what I tried, data1 = Games.objects.order_by('-id')[:2] data2 = sorted(Games.objects.exclude(id__in=data1), key=lambda x: random.random())[:2] But now I'm stuck, I was wondering how can I combine the games present in data1 & data2 variables into a single variable data3. Here's what I tried, data3 = Games.objects.filter(Q(id__in=data1) | Q(id__in=data2)) But it's raising an error, int() argument must be a string, a bytes-like object or a number, not 'Games'. How can we do that? Thank You :) -
AttributeError: type object 'Newmodel' has no attribute 'get' in django dynamic model creation?
I want to create a dynamic model based on my csv file.I followed Django general approach (DynamicModel) In views.py my code should looks like ` def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None): """ Create specified model """ class Meta: # Using type('Meta', ...) gives a dictproxy error during model creation pass if app_label: # app_label must be set using the Meta inner class setattr(Meta, 'app_label', app_label) # Update Meta with any options that were provided if options is not None: for key, value in options.iteritems(): setattr(Meta, key, value) # Set up a dictionary to simulate declarations within a class attrs = {'__module__': module, 'Meta': Meta} # Add in any fields that were provided if fields: attrs.update(fields) # Create the class, which automatically triggers ModelBase processing model = type(name, (models.Model,), attrs) # Create an Admin class if admin options were provided if admin_opts is not None: class Admin(admin.ModelAdmin): pass for key, value in admin_opts: setattr(Admin, key, value) admin.site.register(model, Admin) return model Under this function i added this code def upload_csv(request): data = {} if request.method == "GET": return render(request, "upload_csv.html", data) # if not GET, then proceed try: csv_file = request.FILES["csv_file"] if not csv_file.name.endswith('.csv'): messages.error(request,'File is not CSV type') return HttpResponseRedirect(reverse("upload_csv")) … -
migrating to Django 1.11 django-hvad error
I'm new to Django. Trying to migrate from django==1.8.5 to 1.11 django-hvad package is essential for me, however, when upgraded to django==1.10, it throws the assertion error about the Django version. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f407d733b70> Traceback (most recent call last): File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/home/riddle/pro/blog/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/riddle/pro/blog/app/apps/frontend/website/models.py", line 116, in <module> class ContentBlock(Common, TranslatableModel, OrderedModel): File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/django/db/models/base.py", line 309, in __new__ new_class._prepare() File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/django/db/models/base.py", line 359, in _prepare signals.class_prepared.send(sender=cls) File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 191, in send response = receiver(signal=self, sender=sender, **named) File "/home/riddle/pro/blog/env/lib/python3.6/site-packages/hvad/models.py", line 447, in prepare_translatable_model … -
Friendly return message when POST or GET fails or succeeds
How do I get a friendly message returned to my client when a GET or POST succeeds of fails? serializers.py class BrandSerializer(serializers.ModelSerializer): """ Class to serialize Brand objects """ class Meta: model = Brand fields = '__all__' read_only_fields = 'id' class BrandSignupSerializer(serializers.Serializer): """ Create Brand profile """ name = serializers.CharField(required=True, write_only=True) brand = serializers.CharField(required=True, write_only=True) email = serializers.EmailField(required=True, write_only=True) phone = serializers.CharField(required=True, write_only=True) website = serializers.CharField(required=True, write_only=True) class Meta: model = Brand fields = ('name', 'brand', 'email', 'phone', 'website') unique = 'email' def create(self, validated_data): brand = Brand.objects.create(**validated_data) brand.save() return brand def update(self, instance, validated_data): pass views.py class BrandList(generics.ListAPIView): """ List all Brands HTTP: GET """ queryset = Brand.objects.all() serializer_class = BrandSerializer class BrandDetail(generics.RetrieveUpdateDestroyAPIView): """ List one Brand HTTP: GET """ queryset = Brand.objects.all() serializer_class = BrandSerializer class BrandSignup(generics.CreateAPIView): """ Brand signup HTTP POST """ queryset = Brand.objects.all() serializer_class = BrandSignupSerializer def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) return Response(data=serializer.data, status=status.HTTP_201_CREATED) -
I needs anwser to this books exercise : Software Testing Concept and Operations by Ali Mili,Faizouz TChier
Some of the questions 1. For each relation R given here on space S defined by natural variables x and y, tell whether R has the properties defined in section 4.2.3 a. R ={s, s')| x +y = x'+y'} b. R ={s, s')| x' = x' +1 ^ y'=y-1} c. R ={s, s')| x > x' ^ y'=y} d. R ={s, s')| x -y >= x'-y'} e. R ={s, s')| x >=1 ^ y >= x } Consider the specification of the search programs, given in section 4.3.2. Write five new interpretations, along with corresponding relations. Hint : consider, for example, the situation where a and x are preserved whether x is or is not in a; or the case where no output requirement is imposed when x is not in a. Please help me . It really helps me for my study in this subjects . TQ -
Django model unique together both ways
Many questions already on this topic, but not what i'm searching for. I have this Model: class Options(TimeStampedModel) option_1 = models.CharField(max_length=64) option_2 = models.CharField(max_length=64) class Meta: unique_together = ('option_1', 'option_2') Now I have a unique constraint on the fields. Is there a way to also define this the other way around so that it doesn't matter what was option_1 and what was option_2 As example: Options.create('spam', 'eggs') # Allowed Options.create('spam', 'eggs') # Not allowed Options.create('eggs', 'spam') # Is allowed but should not be Thanks in advance! -
Django model creation for an existing application
I want to implement Organisation,department and user relation model. Where in super user of organisation can add departments along with department details like phone, address, email etc. A user can belongs to one are more departments, and user with department owner or organisation super user can edit user info as well department info. After analysis,I came up with below model relation. class Organization(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Departments(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) email= models.CharField(max_length=30, unique=True) phone= models.CharField(max_length=30) org_linked=models.ForeignKey(Organization) user_linked=models.ForeignKey(User) I have already running application which has few got models and few users info already created, becasue of this I am not sure, how to link existing user to above two models and where to add super users relation. Please guide me on this -
Django, Python: Bulk create for several dependencies
I have a lot of dependencies (Group->Link->Match) - and I can not create a new one object without a id for ForeignKey. There is method is to simplify or speed up this operation? Can I create a large object that saves required dependencies? I try to do it via bulk_create - but same problem with id. groups = template.get('groups') allMatchObjs = [] if groups: for group in groups: groupObj = Group.objects.create(name=group['name']) links = group.get('links') if links: for link in links: linkObj = Link.objects.create( group=groupObj, name=link['name'] matches = link.get('matches') if matches: matchObjs = (Match( name=match['name'], link=linkObj) for match in matches) allMatchObjs.extend(matchObjs) Match.objects.bulk_create(allMatchObjs) -
django templates: concatenate a string with an id inside a name input
I'm working with Django forms and widget_tweaks, and I need to create an input that has html like this <input type="text" name="designation{{ vente.id}}" value="{{ vente.designation }}" /> I've tried : {% render_field modifier.designation class="form-control" value=vente.designation placeholder="désignation" name="designation"+vente.id %} I get the value exactly like I need, However I can't get the concatenated string of name, there is something with the concatenation. PS: {{ vente.id}} is an id from my database Thank You for your help -
Building a priority list of models
How can I build a Django model (or dictionary/list) to define a priority list to my CategorySources model? class Category(models.Model): name = models.CharField('Name', unique=True, max_length=35) description = models.CharField('Description', max_length=255) slug = models.SlugField('Shortcut') class Source(models.Model): name = models.CharField('Name', unique=True, max_length=35) description = models.CharField('Description', max_length=255) class CategorySource(models.Model): category = models.ForeignKey(Category, related_name='category_source') source = models.ForeignKey(Source, related_name='category_source') url = models.CharField('RSS Feed Url', max_length=2000) I want to create a model or dictionary that says, for category X use first the source Y, then source Z, then source W, etc. I thought about adding a priority number in CategorySource model but it would be hard to manage if I have a lot of categories and sources... -
How to connect checkbox button with each courses in choicefield
Please I don't know how to connect checkbox button to each course in the ChoiceField Turple and likewise the course_code will be on the same line with courses... Pls i need a solution on how to go about it.... class Course(models.Model): COURSES_CHOICES = ( ('maths', 'Mathematics'), ('eng', 'English'), ('bio', 'Biology'), ('chem', 'Chemistry'), ) course_names = models.Charfield(choices=COURSES_CHOICES, null=True,) course_code = models.IntergerField() class Department(models.Model): name = models.Charfield(max_length=30) student = models.ForeignKey(User) course = models.ManyToManyField(Course) -
Make a form object in Django and run is_valid method
I am trying to make a form object in Django views and run the is_valid() method on it. I have tried 1. form = LandingPageForm(initial={'user':user, 'name':"Shahrukh") and 2. form = LandingPageForm(data={'user':user, 'name':"Shahrukh") but running form.is_valid() method returns false both the times, I also tried 3. form = LandingPageForm({'user':user, 'name':"Shahrukh") but is_valid() returned false, even though there were no errors. Please note I have tried printing form.errors and form.non_field_errors() both of which returned empty is the case 3. I want to know how can we create a form object in Django views and run is_valid() on it -
Django views for statistics
I am currently facing a problem with creating a statistical overview of my app. The app contains a geodjango multipoligon model (Area) that other models (Hotels,Cafes,Museums etc.) reference for their location: class Area(models.Model): area_name = models.CharField(max_length=100, null=True, blank=True) mpoly = models.MultiPolygonField(srid=4326, null=True, blank=True) class Hotel/Restaurant/Museum/Traffic_Incident(models.Model): area = models.ForeignKey(Area) Is it possible to create a view in django where I can show all kinds of places within the area (Area model)? Due to specific reasons I do not want to mix the other models together. What I am looking for is a way to create a map with all the objects on the map as well as statistics on what types of establishments are in the area. I have no trouble with creating a map and passing the geojson data to django-leaflet, but I am struggling to create a table with statistics regarding the actual places in the area. I can make something like this by creating a model for the statistics, but I am reluctant to do that, because the data would be dynamic and I do not want to create a simple counter for statistics, although I might have to do just that if there are no other options. -
Django request.POST.getlist() returns empty
I am trying to extract a posted array in Django 2. I am posting the following: sprints[0][id]: 5 sprints[0][name]: Test sprint 1 sprints[0][order]: 0 sprints[0][project]: sprints[0][start]: sprints[0][end]: sprints[1][id]: 6 sprints[1][name]: Test sprint 2 sprints[1][order]: 1 sprints[1][project]: sprints[1][start]: sprints[1][end]: This returns the data visibly def single(request, id): return Response(request.POST) However this return it as an empty list ([]). def single(request, id): return Response(request.POST.getlist('sprints')) As does this. def single(request, id): return Response(request.POST.getlist('sprints[]')) Why? -
Want to deploy my web based application using django
I want to deploy my software on the local machine of the client so that it can work offline but do not want to share the source code as it can easily be stolen and they can make a replica of that. I need to encrypt my back end python django files so that they can not understand that and can not even edit them. I have researched on obfuscator but did not understand much how can i use it for my python files it is helpful if i want to obfuscate html or java script files but did not find any help for python files. Is there any other way to encrypt and decrypt my python back end code only for the web application that is needed to work locally? -
Django: No reserve match
Hello i don't undertand why i have this error. I can't see the problem, i tried solve the url in the html. NoReverseMatch at /admin/product_list/20/edit/ Reverse for 'edit_product' with keyword arguments '{u'product_id': ''}' not found. 1 pattern(s) tried: ['admin/product_list/(?P<product_id>\\d+)/edit/$'] Request Method: GET Request URL: http://127.0.0.1:8000/admin/product_list/20/edit/ Django Version: 1.11.11 Exception Type: NoReverseMatch Exception Value: Reverse for 'edit_product' with keyword arguments '{u'product_id': ''}' not found. 1 pattern(s) tried: ['admin/product_list/(?P<product_id>\\d+)/edit/$'] Exception Location: /usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py in _reverse_with_prefix, line 497 Python Executable: /usr/bin/python Python Version: 2.7.12 My url: url(r'^admin/product_list/(?P<product_id>\d+)/edit/$', views.admin_zone_edit_product, name='edit_product'), My html: {% extends 'admin/baseadmin.html' %} {% load staticfiles %} {% block content %} {% csrf_token %} <div ><form id="login" action="{% url 'edit_product' product_id=product.id %}" method ="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Save"></input> </form></div> {% endblock %} -
Django __call__() missing 1 required keyword-only argument: 'manager'
I have two models: class Someinfo(models.Model): name = models.CharField(max_length=200) #something else class OtherInfo(models.Model): name2 = models.CharField(max_lenth=200) related_someinfo = models.ManyToManyField(Someinfo) #something else Now I have created CBV views to create and view them. The CreateView works fine and saves info that can be reviewed in admin, but I cannot get the template to display the data on any other view be it FormView, DetailView or any other, because I get this error: __call__() missing 1 required keyword-only argument: 'manager' Request Method: GET Request URL: http://something Django Version: 2.0.3 Exception Type: TypeError Exception Value: __call__() missing 1 required keyword-only argument: 'manager' Exception Location: /usr/local/lib/python3.5/dist-packages/django/forms/forms.py in get_initial_for_field, line 494 Python Executable: /usr/bin/python3 Python Version: 3.5.3 Checking the line in forms.py it shows that the function that is not working is: def get_initial_for_field(self, field, field_name): """ Return initial data for field on form. Use initial data from the form or the field, in that order. Evaluate callable values. """ value = self.initial.get(field_name, field.initial) if callable(value): 494: value = value() return value Any suggestions? I can query the linked objects via shell and they are saved in the database, so I have no idea how to proceed. -
Django session timeout after 10 minutes in some browsers while it is valid for one day(in settings.py)
I am using Django Basic authentication and Session authentication inbuilt API.In my application I have given a session timeout value of 24 hours in settings.py. It is working fine but in some chrome browsers it is doing session timeout at every 10-15 minutes. I have checked session cookie after successful login it is showing correct expiry date.but after 10-15 minutes when session timeouts, cookie expiry date automatically changes. Please reply if someone has faced some issue. -
django.utils.encoding.DjangoUnicodeDecodeError : utf8' codec can't decode byte 0x92 in position 15: invalid start byte. You passed in 'Une tentative
probleme avec python manage.py runserver django.utils.encoding.DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 15: invalid start byte. You passed in 'Une tentative d\x92acc\xe8s \xe0 un socket de mani\xe8re interdite par ses autorisations d\x92acc\xe8s a \xe9t\xe9 tent\xe9e' () -
How can i send notifications system to user in 1 hour or 2 hour via Email on Django App
I want to send notification system via email to spesific user and the user can manage when he will get email for that notifications. What recommended django app to do that. Sorry for my bad english -
custom dropdownList in Django
How to make custom dropdownlist in django 1. I have a model class FinancialYearSetting(models.Model): financial_year_setting = models.CharField(max_length=20) def str(self): return self.financial_year_setting class GoalMaster(models.Model): Fy_choices = ( ('2011-2018', '2011-2018'), ('2018-2019', '2018-2019'), ) finacialYr = models.CharField(max_length=10, choices=Fy_choices) employee_code = models.CharField(max_length=50) So I want to make coustom dropdownlist using database without using below syntax finacialYr = models.ForeignKey(FinancialYearSetting, on_delete=models.CASCADE) because I do not want id(pk) values there should be text field and value both should be text. Please suggest how could bind it on html enter code here -
How to validate the sum of a field of many inlineformset in a CreateView?
I have a CreateView of a model with an inlineformset_factory of another model (4 rows, one of each child model). One of the child's model is 'Percentage'. Right now it saves bot the parent and the child model, but I don't have any validation on the percentage field, so the User can easily type '11', '34', '02' and '0' and it will save it. I want to validate that, before saving anything, the sum of the percentage fields are 100%. My forms.py look like this: class ParentForm(ModelForm): class Meta: model = Parent fields = ['name', 'observations'] class ChildCreateForm(ModelForm): class Meta: model = Child fields = ['percentage', 'material'] def clean(self): cleaned_data = super(ChildCreateForm, self).clean() print(cleaned_data['percentage']) ChildCreateFormCreateFormSet = inlineformset_factory(Parent, Child, form=ChildCreateForm, extra=4) So far so good, I can validate every percentage row individually, but I want to validate the total sum. Should I validate the form with Javascript? There is a way with Django? Or it is best a third option? -
Unit testing delete and update images with django
I have an inlineformset using my imagemodel. It has a foreignkey to my lodging model defined like this: ImageFormset = inlineformset_factory(Lodging,ImageModel,fields=('image',), can_delete=True,form=ImageForm,extra=0) I can get lodging_id from url and can use it to create an instance of lodging. I, then, pass it to my ImageFormset instance lodging=Lodging.objects.get(id=ad_id) formset = ImageFormset(instance=lodging) In this way, I will get some initial-forms. My question is what should I pass as data in unit testing. What I have tried so far is: data = { 'imagemodel_set-TOTAL_FORMS': 2, 'imagemodel_set-INITIAL_FORMS': 2, 'imagemodel_set-0-image': SimpleUploadedFile('test_image1.jpg', get_binary_data(self.image3_location), content_type='image/jpeg'), 'imagemodel_set-1-image': SimpleUploadedFile('test_image2.jpg', get_binary_data(self.image4_location), content_type='image/jpeg'), } But this is giving me error: "['ManagementForm data is missing or has been tampered with']" Any help would be appreciated. -
Export file in csv is not working in django
I'm currently trying to export a csv file if the print button is clicked. The problem is the file which generated is not .csv file However, the file content is retrieve the values which I need (I checked by changing data type of file manuallly). Could anyone show me the mistakes? Or is it related to any requirement plugin? Any and all help is greatly appreciated! import csv query_data = search_data(request,request.user.userid) if (request.method == 'POST'): if 'csvexport' in request.POST: data = csv_export(query_data) return HttpResponse (data,content_type='text/csv') -- def csv_export (data): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="file.csv"' writer = csv.writer(response) response.write('\ufeff'.encode('utf8')) writer.writerow([,'valData' ,'value1' ,'value2']) for rec in data: writer.writerow([rec['valData'] ,rec['value1'] ,rec['value2']]) return response -- def search_data(request,userid): cursor = connection.cursor() query = str("SELECT\n" " valData,\n" " MG0.valData as value1,\n" " MG1.valData as value2,\n" " FROM\n" " T_USER AS TU\n" " LEFT JOIN M_GENERAL AS MG0\n" " ON MG0.Cd='001'\n" " LEFT JOIN M_GENERAL AS MG1\n" " ON MG1.Cd='001'\n") cursor.execute(query) row = dictfetchall(cursor,) return row -
Alert from HTML script in Django
I am prying to display alert in my Django project. I am passing values from views.py to singup.html to display alert based on condition. But initially my alert variable in HTML doesn't get value. Only after clicking on Submit button alert is initialized and displays the required alert. Views.py def signup(request): d = {} data={} template={} context={} print(request.POST) if request.method == 'POST': form = RegisterForm1(request.POST) print("hello212") if request.POST.get('email1') and request.POST.get('password1'): post = Register1() post.email = request.POST.get('email1') post.password = request.POST.get('password1') post.repeatpassword=request.POST.get('repeatpassword1') print(post.email) print(post.password) print(post.repeatpassword) data=Register.objects.filter(email__iexact=post.email).exists() print (data) if post.password == post.repeatpassword: if data == False: post.save() alert = 0 print("check") else: alert = 2 context={ "alert":alert, } print (context) # template= "personal_anshul/signup.html" return render(request, "personal_anshul/signup.html", context) Signup: <input type="hidden" name="alert" value="{{alert}}" readonly> <script> function check() { <!--{% for message in messages %}--> <!--<div class="alert alert-{{ message.tags }}">{{ message }}</div>--> <!--{% endfor %}--> <!--alert("check")--> console.log({{ alert }}) if ({{alert}} == 2) { alert("id exists") } else{ alert("You Genius!") } } </script> Alert value when i go to my page for the first time: enter image description here Alert value after i click on submit button: enter image description here How to initialize alert so that i get a value to compare my …