Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM cache
I have several models with one-to-many relationships. In my management commands I need to iterate over all entities multiple times. I.e. I have multiple loops like this: for childEntity in dbObj.childEntities.all(): .... Does Django use session cache for dbObj.childEntities.all()? Or I need to cache results somehow? -
PHP Post to Django
I am trying currently to accomplish the following: I have a server, where a PHP-Application is running on. I have to extract some files and send them to another server (Django) with a POST request. I am trying to accomplish this by using cURL. I already have a couple of POST requests running and they all work as needed, but as soon as I try to accomplish this with a file I am running into issues. When I try to send a file from Javascript to my Django Server with Multipart and FormData, everything works. I tried to use the following code in PHP: public function httpPost($url, $data, $multipart) { $curl = curl_init($url); if ($multipart) { // curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data')); // curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // curl_setopt($curl, CURLOPT_INFILE, $file_handle); } else { curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); } curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($curl); if ($response === false) { var_dump(curl_error($curl)); } curl_close($curl); } As you can see from the above code-snippet, I am trying to set the Header to Multipart and set the data accordingly. I tried the following things already: load the file into PHP with fopen/fread then set it in the $data array. Then … -
Convert to Excel with Django
I want to be able to convert some Django model to a Excel file. My view is as follows: @login_required def archive_to_excel(request): calculations_list = Calculations.objects.filter(user=request.user) \ .values_list('make', 'model', 'first_registration', 'body', 'facelift', 'engine', 'transmission', 'purchase_price', 'mileage', 'customer__firstname', 'customer__lastname', 'customer__email') \ .order_by('-id') columns = [_('Make'), _('Model'), _('First registration'), _('Body'), _('Facelift'), _('Engine'), _('Transmission'), _('Price'), _('Mileage'), _('Customer first name'), _('Customer last name'), _('Customer email')] return convert_to_excel("archive", columns, calculations_list) And convert_to_excel function is as follows: def convert_to_excel(file_name, columns, values): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="{}.xls"'.format(file_name) wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet(file_name.capitalize()) # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() for row in values: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response That works fine, but the problem that I have is that the purchase_price in Calculations model is stored EXCL VAT and I want to show it in the excel file INCL VAT. How can I multiply the purchase_price with 1.21 and show it in the excel file? Any advice? -
Where can I find the SECRET_KEY of existing Mezzanine Project?
I am trying to upload my existing mezzanine project in pythonanywhere.com. However, I always get an error that the SECRET_KEY should not be empty. When I looked into the settings.py, the SECRET_KEY is not there. In the mezzanine documentation, it says that the SECRET_KEY is automatically created after the command "mezzanine-project". But, where is it? How do I know the SECRET_KEY? Thank you! -
Issue upgrading Django from 1.8 to 1.9
I am trying to upgrade Django from 1.8 to 1.9 but, when I run migrations it's throwing up error. Below is the stack trace. Stack trace This is because of a new migration introduced in Django 1.9 which is to move auth username unicity logic from form to model [ref: ticket ]. But, before upgrading we have implemented a little hack mentioned here to increase username character length from the default 30 character length to 75 characters. Now, when I run migrations it's considering only the first 30 characters of username and throwing up Integrity Error. Is there a way around this ? I don't want to go for a custom auth model as there are lot of complications involved. -
Django OAuth2 unsupported_grant_type
I'm trying to send a request to get an access_token with OAuth2. I'm executing this code : r = requests.post(url, data={ "form": { 'username': username, 'password': password, 'grant_type': 'password', 'client_id': 'xxx', 'client_secret': 'xxx' }, "headers": { "Content-Length": "23", "Accept-Encoding": "identity, deflate, compress, gzip", "Accept": "*/*", "User-Agent": "python-requests/0.8.0", "Content-Type": "application/x-www-form-urlencoded" } }) When I send this request I get this error : {'error': 'unsupported_grant_type'} Thanks for your help ! -
Update model field in Django with button click on a template
I am new to Django and I am having some troubles with my first web application. My idea is to show a template on user first login with some information about the web. The template contains an "accept button" and a "continue to the webpage" button. This template should appear everytime the users login, until they click on the accept button. I have created a new model with userID, a boolean field (terms_accepted) and a date field (terms_accepted_date) to control if the users have accepted the information, and the date when they have done so. What I want is to update the terms_accepted (from False to True), when the users click on the accept button. Is there a simply way to modify the model from the template? I have created the correct flow, because If I modify manually the terms_accepted field from the admin site, when I enter to the page I don't see the template with the information. However, I don't know how to update the field automatically on button click. Thanks -
JavaScript and Jquery books
I'm new to web development but I know css, html and Django but I don't have knowledge of JavaScript and Jquery what book would you recommend for me as a Django developer -
How to pass only year from url to view
I have my django app and I want to pass from url to view years in format, for example: 2017-18. Below I got an error that my date have to be in date format - YYYY-MM-DD. Here is my url: url(r'^(?P<branch_slug>/production/(?P<year1>[0-9]{4})-(?P<year2>[0-9]{2})$', Events.as_view()), Here is my view: def get_queryset(self): season = Events.objects.get(start=self.kwargs['year1'], end=self.kwargs['year2']) filter_['start__gte'] = season.start filter_['start__lte'] = season.end return self.model.objects.filter(**filter_) -
Deploying Django App to Heroku (Procfile and Build Structure)
I new in Django also Heroku. I want to know if my Project have structure like this : src/ admin/ __init__.py wsgi.py urls.py settings.py myapp/ migrate/ 0001_initial.py __init__.py static/ templates/ __init__.py admin.py apps.py models.py tests.py manage.py views.py What my Procfile must be? I try anything Procfile. Build log say have deployed but it can't run. When I try heroku logs I got error about no module named myapp. That error just example. I try using web: gunicorn myapp to raise that error. What module I must fill to be found? I realy confuse where they placed my app. Maybe also any suggestion what file must I edited too. Thank you. -
Django strip whitespaces in CharField
I am trying to populate data into the following model from a csv and using update_or_create() in a loop to do that. class TargetPlace(models.Model): name = models.CharField(max_length=100) The csv may have some entries which have leading or trailing white spaces and I want to get rid of those. I saw that CharField's in Django >=1.9 have a strip argument that takes care of this by default (since its True by default). I am using Django 1.10 but still seeing duplicate entries in the model (those with and without leading white spaces). Does the strip argument not work that way? -
Trumbowyg editor doesn't render when I use TrumbowygWidget as the widget for a form field
I've downloaded the Trumbowyg WYSIWYG editor: http://alex-d.github.io/Trumbowyg/ as well as django-trumbowyg for integrating it with django: https://github.com/sandino/django-trumbowyg I'm using this for my content field in my form Here's the form: class PostForm(forms.ModelForm): content = forms.CharField(widget=TrumbowygWidget(), required=False) title = forms.TextInput(attrs={'placeholder': 'title'}) class Meta: model = Post fields = [ 'title', 'content', 'category', 'image', 'id', 'user' ] template ... {{ form_post.content }} ... just renders a plain textarea, but it should be rendering the Trumbowyg editor. I tried <div id="trumbowyg-demo"></div> and that successfully renders the Trumbowyg editor, so I don't what's wrong. If anyone can suggest what a problem would be thad be great. PS: the downloaded django-trumbowyg was put in site-packages and the actual Trumbowyg WYSIWYG editor was put in static > js, not sure if that affects. anything. -
Postman Nested Foreign Key Error
I'm having trouble sending data to to my form using postman. It gives the following error. {"user":["This field is required."]} I'm using the built in user models and trying to map it with my custom fields in userinformations models. models.py class UserInformation(BaseModel): user = models.OneToOneField(User, related_name='user_id') first_name = models.CharField(max_length=45) middle_name = models.CharField(max_length=45, null=True) last_name = models.CharField(max_length=45) vendor = models.BooleanField(default=True) phone = models.CharField(max_length=100, validators=[ RegexValidator(regex=r'^\+?8801?\d{9}$', message="Phone number must be entered in the format: '+8801*********'") ], blank=False, unique=True) date_of_birth = models.DateField() confirmation_token = models.CharField(max_length=45, null=True) confirmation_exp = models.DateTimeField(null=True) pw_reminder_token = models.CharField(max_length=45, null=True) pw_reminder_exp = models.DateTimeField(null=True) profile_pic = models.ImageField(blank=True, null=True, upload_to='profile_images/', default='Images/none/no_images.jpg') cover_photo = models.ImageField(blank=True, null=True, upload_to='cover_images/', default='Images/none/no_images.jpg') thumbnail_pic = models.ImageField(blank=True, null=True, upload_to='thumbnail_images/', default='Images/none/no_images.jpg') phone_verified = models.BooleanField(default=False) email_verified = models.BooleanField(default=False) reward_points = models.IntegerField(null=False, default=0) ref_code = models.CharField(null=True, max_length=10) def __str__(self): return self.user.username def delete(self, *args, **kwargs): self.user.delete() super(UserInformation, self).delete(*args, **kwargs) serializers.py class UserSerializer(ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}, write_only=True) email = serializers.EmailField(validators=[required]) class Meta: model = User fields = ['username', 'email', 'password', 'is_active'] extra_kwargs = {'password': {'write_only': True}, } def validate(self, data): email = data.get('email', None) user = User.objects.filter(email=email).distinct() if user.exists(): raise ValidationError("That email is already registered!") return data class UserProfileSerializer(ModelSerializer): user = UserSerializer(required=True) profile_pic = serializers.ImageField(use_url=True, required=False) cover_photo = serializers.ImageField(use_url=True, required=False) thumbnail_pic = … -
tastypie - giving 401 in tests but not in shell or postman
When I am trying to run tests for patching a list, I am getting 401 in tastypie/resources.py at line response = callback(request, *args, **kwargs) and its going to exception line: except Exception as e: import ipdb; ipdb.set_trace(); # Prevent muting non-django's exceptions # i.e. RequestException from 'requests' library if hasattr(e, 'response') and isinstance(e.response, HttpResponse): return e.response When I tried to print "e", it is empty ''. But returning 401. Also, I am getting the same error when I am trying to patch(from anywhere shell or postman) list of resources along with their related resources. If I dont modify related resources, it is not giving error. -
Django manage.py collectstatic SuspiciousFileOperation
I'm working on combining React with Django 1.10 and am getting pretty funky activity when trying to configure the pipeline. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Matt\Envs\my-site\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Matt\Envs\my-site\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Matt\Envs\my-site\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Matt\Envs\my-site\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Users\Matt\Envs\FUUD\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 193, in handle collected = self.collect() File "C:\Users\Matt\Envs\FUUD\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 139, in collect for original_path, processed_path, processed in processor: File "C:\Users\Matt\Envs\my-site\lib\site-packages\pipeline\storage.py", line 26, in post_process packager.pack_stylesheets(package) File "C:\Users\Matt\Envs\my-site\lib\site-packages\pipeline\packager.py", line 96, in pack_stylesheets variant=package.variant, **kwargs) File "C:\Users\Matt\Envs\my-site\lib\site-packages\pipeline\packager.py", line 105, in pack paths = self.compile(package.paths, force=True) File "C:\Users\Matt\Envs\my-site\lib\site-packages\pipeline\packager.py", line 34, in paths return [path for path in self.sources File "C:\Users\Matt\Envs\my-site\lib\site-packages\pipeline\packager.py", line 27, in sources if path not in paths and find(path): File "C:\Users\Matt\Envs\my-site\lib\site-packages\django\contrib\staticfiles\finders.py", line 250, in find result = finder.find(path, all=all) File "C:\Users\Matt\Envs\my-site\lib\site-packages\django\contrib\staticfiles\finders.py", line 160, in find match = self.find_in_app(app, path) File "C:\Users\Matt\Envs\my-site\lib\site-packages\django\contrib\staticfiles\finders.py", line 174, in find_in_app if storage.exists(path): File "C:\Users\Matt\Envs\my-site\lib\site-packages\django\core\files\storage.py", line 394, in exists return os.path.exists(self.path(name)) File "C:\Users\Matt\Envs\my-site\lib\site-packages\django\core\files\storage.py", line 407, in path return safe_join(self.location, name) File "C:\Users\Matt\Envs\my-site\lib\site-packages\django\utils\_os.py", line 78, in safe_join 'component ({})'.format(final_path, base_path)) django.core.exceptions.SuspiciousFileOperation: The joined path (C:\) is located outside of the base … -
I am new to django framework started few days back for creating tool.
I am new to django framework started few days back for creating tool. Have installed python 3.6 and django 1.8 . Have to upload excel sheet data to list objects and do some concatenation .provide the results as in the HTML form itself in the django framework. Please provide me tutorial step by step i to work on this High level work : Need to generate the SQl query based on Mapping spec for ETL projects: Excel data Is ETL mapping spec with table names and column names Output should be : Full sql Query -
Change desktop web pages to mobile web pages when someone logs in using mobile
I have developed some site using Django. It works fine for desktop. But on mobile i need to zoom out to view the page. Can anyone help me with settings to be added for changing desktop web pages to mobile pages so that they will get fit in mobile screen size. Thanks -
Instead of customizer name, how can I show url of cutomuser
enter image description here In the owner field there is cutomuser name (changja88) Instead of customizer name, how can I show url of cutomuser Thank you ! -
Cannot connect to server without using connection.getResponseCode()?
Why i cannot connect to server(Django Server) without using connection.getResponseCode() == HttpURLConnection.HTTP_OK from android client Application? -
How to join two models in django-rest-framework
Let say i have two tables(model) level: id file_number status level_process: process_ptr_id level_id I want to combined both of my table above to display it in one API using djang-rest-framework.. I'm looking for the example on the internet and i cannot find it..by the way i'm using python 2.7 , django 1.10.5 and djangorestframework 3.6.2 -
Adding permissions to Django model without table
I'm working on some Django Rest Framework based project (quite expected API for some web-app). It has as traditional Django models, and some kind of model-like objects: they behave like Django models but don't store anything in DB. No tables, no content-types. When we ask them for objects, they goes to external API and forms resulting Queryset. Now I need to build some role-based access system. To make the architecture clear and extensible, I want to make groups and permissions managable through the Django Admin interface. So, I guess, we need to put some permissions to DB and then we'll be able to add these permissions to user groups. After that, we'll check these permissions in DRF.permissions class. But since we have neither tables, nor content-types for these 'models', we can't add records to permissions table right now. What is the right way to make this possible? Should I rebuild these 'models' through the metaclass with proxy = True? Or should I add a proxy layer above? Maybe I should add some dummy content-types by hand? -
In django, how to return value and also raise ValidationError after a form is invalidly edited?
I would like to return value and raise ValidationError after a form is invalidly edited at the same time. Is it achievable? -
Store object for later in django app's `ready`
I have a Django project that includes an app with a ready method. I use the ready method to create a Pubnub listener object. The code looks something like this: # myproject/myapp/apps.py from pubnub.callbacks import SubscribeCallback from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub from django.apps import AppConfig from somewhere import SomeNamespace class MySubscribeCallback(SubscribeCallback): def message(self, pubnub, message): # store the message in the database class MyPubnub(PubNub): def __init__(self): pnconfig = PNConfiguration() pnconfig.subscribe_key = 'demo' pnconfig.publish_key = 'demo' super(MyPubnub, self).__init__(config=pnconfig) self.add_listener(MySubscribeCallback()) self.subscribe().channels('demo').execute() class MyAppConfig(AppConfig): name = 'myapp' def ready(self): SomeNamespace.my_pubnub_listener = MyPubnub() Where is the appropriate namespace to store my_pubnub_listener? Will it get cleaned up after startup if I just put it in self.my_pubnub_listener? Is there a better place for it? -
Django filter by multipleChoiceField
I have model Skill class Skill(models.Model): hero= models.ForeignKey(Hero) name = models.CharField(max_length=255) And I have model Hero class Hero(models.Model): name = models.CharField(max_length=255) I use multiple choice field to select skills OPTIONS = ( ("sharingan", "sharingan"), ("rasengan", "rasengan"), ("fireball", "fireball"), ) skills= forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=OPTIONS) I use get request to send my form and my search page url becomes something like: mysite.com/search?skills=shiringan&skills=rasengan In my views.py I have def vip(request): heroes = Hero.objects.all return render(request, 'app_name/search.html',{'heroes': heroes}) What should I write in views.py to select all heroes with chosen skills? -
How set Django foreign key with it own id
Example My post belong to a user Post->User so if I want the post, I have to use. /user/iamadog/post/999 So I want just to use /post/1234 or /post/1234-is-the-best-password How to set my model like that?