Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fp.write writes extra newlines to file
So I have a form in Django, where user inputs some text. Then I write this text to a file. My views.py looks something like this: if request.method == "POST": code = request.POST.get('code', False) fp = open('mp/somefile.txt', 'w') fp.write(code) fp.close() However this causes extra newline characters. (I am using windows) for example aaaaaaaa bbbbbbbb cccccccc results in aaaaaaaa bbbbbbbb cccccccc Is there a way to prevent these extra newline characters? -
Django - forloop.counter numbers not resetting when using nested for loops
I have a need for counting the standings of a sport team based on the total points they have their division. Each team has a total points and division assigned to them. My django template code is as follows: {% for division in divisions %} <h4>{{ division }}</h4> <table class="table"> <tr> <td align="center">Place</td> <td>Team</td> <td align="center">Points</td> </tr> {% for stat in stats %} {% if stat.division == division %} <tr> <td width="10%" align="center">{{ forloop.counter}}</td> <td width="70%">{{ stat.team }}</td> <td width="20%" align="center">{{ stat.points }}</td> </tr> {% endif %} {% endfor %} </table> {% endfor %} The problem right now is that say i have 6 teams and 3 are in Division A and 3 are in Division B. Because it is separating the teams based on division it is showing the forloop.counter as 1 through 6 on the first forloop for divisions. What I want it to do is only do the forloop counter for the nested forloop ( the second one for stats ) so that it shows places 1 through 3 for Division A and 1 through 3 for Division B. The results I am getting are: Division A Place Team Points 1 Timberlea Beverage Room 1 7 3 … -
Require Email When Creating an Account with Django
I've got a Django project, which requires users to be able create accounts to access content. I'm using the UserCreationForm to do this. In views.py I have def register_user(request): if request.method == "POST": user_form = UserCreationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data["password1"]) new_user.save() template = "account/registration/registration_done.html" context = {"new_user": new_user} else: # TODO: Handle exception raise BaseException elif request.method == "GET": user_form = UserCreationForm() template = "account/registration/register.html" context = {"user_form": user_form} else: raise NotImplementedError return render(request, template, context=context) And then my template is: {% extends "base.html" %} {% block title %}Create an Account{% endblock %} {% block content %} <h1>Create an Account</h1> <form action="." method="post"> {{ user_form.as_p }} {% csrf_token %} <p><input type="submit" value="Create my account"></p> </form> {% endblock %} Which works okay. But when the create account form is displayed, it only has fields for the username, password, and password verification. There's no requirement that the user enter a valid email. What I'd like to do is have a have the user be required to enter an email address, and then send them an email to ensure that the address is valid, and that they have access to is etc. Surely this is a common enough pattern that there's … -
Django: hashlib keeps generating same hex digest
I have a model like this: class Book(models.Model): hash = models.CharField(max_length=56, unique=True, null=True, editable=False) created_at = models.DateTimeField('Created at', auto_now_add=True) # .. and other fields def save(self): if self.hash is None: string_seed = str(self.created_at).encode('utf-8') + str(self.pk).encode('utf-8') self.hash = hashlib.sha224(string_seed).hexdigest() super(Book, self).save() But I keep getting this error "Duplicate entry 'c19c...abb5' for key 'store_book_hash_4517c5ea_uniq'" after inputting second data (book, in this case). I don't know why my code keeps generating same value. I use django admin page for data entry, and I thought when inserting new book via "Add book" form in django admin, the self.hash should always be None, so new random value would be freshly generated (but in my case, it wouldn't and threw integrity error instead). I'm confused -
Upload image from Android to django server using Retrofit
I am trying to make an Android application that would post the taken photo to django server using Retrofit framework. My android part: private void uploadFile(Uri filePath) { String path = getRealPathFromURI(filePath); File originalFile = new File(String.valueOf(path)); RequestBody filePart = RequestBody.create(MediaType.parse("multipart/form-data"),originalFile); MultipartBody.Part file = MultipartBody.Part.createFormData("upload", path, filePart); ApiRequestsService.UploadFile(this, new OnApiResponseListener() { @Override public void onApiComplete(Object object) { RetrofitResponse response = (RetrofitResponse) object; Toast.makeText(context, response.success, Toast.LENGTH_LONG).show(); } @Override public void onApiError(Exception e) { } }, "Loading...", file); } @Multipart @POST("/uploadImage/") Call<ResponseBody> uploadFile(@Part("upload") MultipartBody.Part file); In the views.py file on the server side I have: def uploadImage(request): # check to see if this is a post request if request.method == "POST": print request.FILES if 'upload' in request.FILES: print "success!" upload = request.FILES['upload'] else: print "something's wrong" The response I get is: [14/Jan/2018 15:55:24] "POST /uploadImage/ HTTP/1.1" 200 47 MultiValueDict: {} something's wrong -
Django unique together validation with request user
In Django, I need to validate unique_together the (author, title) fields. The problem is that the author is the request.user so what is the best approach to validate the admin form? I have this admin: @admin.register(Document) class DocumentAdmin(admin.ModelAdmin): list_display = ("title",) exclude = ('author',) def save_model(self, request, obj, form, change): """Save ``author`` as request user.""" if getattr(obj, 'author', None) is None: obj.author = request.user super().save_model(request, obj, form, change) I can query inside the save_model() and filter both author and title but that doesn't really work well. I also tried with a forms.ModelForm but I can't manage to get the request.user inside the clean() method. -
Heroku does not look for the DJANGO_SETTINGS_MODULE I've set for it
I'm deploying my first site. I intend to use one settings file for production and one for development. Thus I have this structure: workout | |-\settings | |- production.py |- development.py In order to let heroku know where to find the settings file, I do this: $ heroku config:set DJANGO_SETTINGS_MODULE=workout.settings.production Setting DJANGO_SETTINGS_MODULE and restarting ⬢ workoutcalendar... done, v3 DJANGO_SETTINGS_MODULE: workout.settings.production And push again. Everything should be fine now, right? But no: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 317, in execute remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 994, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 971, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed remote: File "<frozen importlib._bootstrap>", line 994, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 971, … -
Getting a long error while migrating using cmd to 'XAMPP' for database connection
Getting an error while using ->python manage.py migrate firstline216:in ensure_connection self.connect() lastline-> access denied for user'root'@localhost, -
Updating a single object with Django Rest Framework ViewSets and Axios
By default, the DRF ViewSets don't have a patch method. Also, by default, Axios doesn't have an update method. It would seem that in order to update/patch an object using Axios and DRF ViewSets I have to write out specifically how to handle a patch method for every ViewSet. Is it possible to use ViewSets default methods without writing extra code just to handle the Axios patch? -
How can I check activity in my app which is written in Django and Angular 4 and it is deployed on Heroku?
I created application based on REST API. Server is written in Django and has PostgreSQL database, web application is written in Angular 4. Both are deployed separately on Heroku. How can I check activity on this website? I would like to know how many people visited them, how money users is active etc. I short, I need all possible statistics. Any ideas? -
Running celery with supervisord unable to discover tasks
I am using celery 4.1.0 with Django-1.11 and supervisor 3.3.1. For some reason celery is unable to discover the tasks in apps (which are listed in INSTALLED_APPS) when I run celery worker via supervisor. When I run celery from command line it does show the tasks. For example, when I run celery from command line here is the output: Running from command line: /home/ubuntu/Env/oba/bin/celery worker -A oba -l DEBUG - ** ---------- .> transport: amqp://***:**@localhost:***// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 1 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . celery.chord . celery.chord_unlock . celery.chunks . celery.group . celery.map . celery.starmap . contact.tasks.send_email_to_admin_for_member . contact.tasks.send_email_to_admin_for_visitor But when run via supervisord, the output from celery is: - ** ---------- .> transport: amqp://***:**@localhost:***// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 1 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . … -
django RestFrameWork - set user to active
I have a model that related to User.I create user instance with is_active=False.I create some model that generate a token .i need to write some functionality ,if token given from user equals to token that related to user instance ,then account set to is_active=True . this is my structure : models.py: class FirstToken(models.Model): token = models.CharField(max_length=6, blank=True) def __str__(self): return self.token def save(self, *args, **kwargs): chars = string.ascii_lowercase + string.digits size = 6 self.token ="".join(random.choice(chars)for _ in range(size)) super(FirstToken, self).save(*args, **kwargs) class UserProfile(models.Model): """User Profile model """ user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='user_profile') phonenumber = models.CharField(validators=[phone_regex], max_length=17, null=True, unique=True) address = models.TextField(max_length=250) first_token = models.OneToOneField(FirstToken,on_delete=models.CASCADE, related_name='first_token',blank=True) def save(self, *args, **kwargs): token = FirstToken.objects.create() self.first_token = token super(UserProfile, self).save(*args, **kwargs) serializers.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile exclude = ['user','id','first_token'] extera_kwargs = { 'phonenumber' : {'validators': []}, } class ActivateUserSerializer(serializers.ModelSerializer): phonenumber = serializers.CharField() token = serializers.CharField() class Meta: model = UserProfile fields = ['phonenumber', 'token',] def validate(self, validated_data): token = validated_data.get('token') x = validated_data.pop('phonenumber') user = UserProfile.objects.get(phonenumber=x) if token == user.first_token: user.set_is_active = True user.save() else : raise serializers.ValidationError("not correct") return token the error i get is: 'str' object has no attribute 'items' what sould i do for performing to … -
how to handle same form on different pages (DRY)
I have a template called base.html. it contains a fixed search form at top of it. all of my other templates inherit from base.html. I want to my form works on every pages (right now I have 10 different pages). One silly solution is to handle form for every single view, but it is opposite of DRY. So how can I handle my form one time for all of views ? NOTE: base.html is just a template and is not used directly by a view. -
Django can't find my static files after changing to production settings and back
I've been trying to deploy my site this weekend and have thus been meddling with the settings. I one of the unpleasant surprises while doing this have been that my static files have seemingly stopped working on my site. My CSS files and javascript files don't work anymore, as if they aren't found by the site. The only thing I can remember doing with regards to static files was inserting this into settings.py: # The absolute path to the directory where collectstatic will collect static files for deployment. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # The URL to use when referring to static files (where they will be served from) STATIC_URL = '/static/' I removed these settings and replaced them with the original STATIC_URL = '/static/' but alas, the problem remains. Why isn't Django finding my static files anymore? PS: As I'm a noob, I don't know exactly what is relevant from my project for you guys to see, but do let me know and I shall provide additional info. -
I need to create API to query data from Twitter based on search term
Hi i need some references to create API to query data from Twitter based on search term using Django, MongoDB, Elastic Search. It would be really helpful if any one have any references to help. -
How to Create new table(models) whenever a new record is created in Django without interrupt a running server
How to create separate table for each record in models (table with same fields for all models), It should happens whenever the new record in models in aa running server without interruption of server | Id | Station Name | GPS Location | Address | 1 | Station 1 | 35.211898, -101.969547 | Some where | | 2 | Station 2 | 43.793428, -102.658402 | Some where | | ... |.............. | ................... | ...... | | ... |.............. | ................... | ...... | | ... |.............. | ................... | ...... | | n |Station n | xx.xxxxxx, xx.xxxxx | xxxxxx | For these each entries I need separate table(Models) like below mentioned should create automatically , whenever a new record is added All Columns headings(Fields) are same in all the table(models) which are create for the record TABLE NAME: Station 1 | TimeStamp | Temperature | Humidity |...|...|...| 40th Column | |14-Jan-18 11:30:12 | 20.13 C | 15% |...|...|...| xxxxxx | |14-Jan-18 11:30:13 | 20.16 C | 15% |...|...|...| xxxxxx | |14-Jan-18 11:30:14 | 20.11 C | 15% |...|...|...| xxxxxx | |14-Jan-18 11:30:15 | 20.18 C | 15% |...|...|...| xxxxxx | . . . |20-Dec-18 16:14:30 | 30.74 C| … -
Django - admin filter to "Add..." page (Model with more then one FK)
I am trying to filter the "Test" content according to "Plan" selection. enter image description here While models looks like: class TestPlan(models.Model): test_plan_name = models.CharField(max_length=200) def __str__(self): return self.test_plan_name class Test(models.Model): test_plan = models.ForeignKey(TestPlan, on_delete=models.CASCADE) test_name = models.CharField(max_length=200) test_type = models.CharField(max_length=200) manual_ttc = models.IntegerField(default=0) priority = models.IntegerField(default=0) owner = models.CharField(max_length=200) drop_name = models.CharField(max_length=200) test_description = models.CharField(max_length=200) note = models.CharField(max_length=200) ac = models.CharField(max_length=200) def __str__(self): return self.test_name class Result(models.Model): plan = models.ForeignKey(TestPlan, on_delete=models.CASCADE) test = models.ForeignKey(Test) status = models.CharField(max_length=100) version = models.CharField(max_length=100) bug = models.CharField(max_length=100) result_path = models.CharField(max_length=100) def __str__(self): return self.status -
Django receive POST from webhook
Our App is receiving webhooks via POST from our payment processor. When I was building this function I originally had it to GET for testing purposes so I could use the URL to test paramaters. Everything worked fine but now I need to test with fake purchases which sends POST request to our URL. So I updated the code but no new webhooks are being saved in our database now. views.py @require_POST def webhook(request): template_name = 'payment/index.html' hook = Webhook() user = User.objects.get(id=request.POST.get('clientAccnum', '')) hook.user = user hook.clientSubacc = request.POST.get('clientSubacc', '') hook.eventType = request.POST.get('eventType') hook.eventGroupType = request.POST.get('eventGroupType', '') hook.subscriptionId = request.POST.get('subscriptionId', '') hook.timestamp = request.POST.get('timestamp', '') hook.timestamplocal = timezone.now() hook.save() hook.user.profile.account_paid = hook.eventType == 'RenewalSuccess' hook.user.profile.save() return render(request, template_name) models.py class Webhook(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) clientSubacc = models.CharField(max_length=120, blank=True, null=True) eventType = models.CharField(max_length=120, blank=True, null=True) eventGroupType = models.CharField(max_length=120, blank=True, null=True) subscriptionId = models.CharField(max_length=120, blank=True, null=True) timestamp = models.DateTimeField(blank=True, null=True) timestamplocal = models.DateTimeField(blank=True, null=True) I'm firing POST requests now from our payment processor and their support is telling me webhooks are being fired but nothing new is saving in the db. This leads me to believe the views.py code is wrong. Anyway I can test this? -
Gunicorn not using right settings file Django?
In my wsgi.py I am conditionally setting DJANGO_SETTINGS_MODULE to two different files(local and production). On the server I have set "PROD" variable in /etc/profile if "PROD" in os.environ: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings_dev") But, still I am getting an error because right settings file is not being set. So maybe if condition isn't working. See below pic. My gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/myproject/myproject ExecStart=/usr/local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/myproject/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target -
django server doesnt load css when it is run
I have all the static files, but for some reason only the normal html loads with no css. I have tried using collectstatic and creating a new project but it doesn't work on any. STATIC_URL is also specified along with static in the url.py . Nothing seem to be working. -
How to prefill certain fields in a new form with respect to the object detail in view in django
I am rendering a form inside a shop detail My form fields includes name, address, shop, booking_date I want to render the form inside of the object detail with only the shop name already prefilled because its inside of the shop detail the form is in -
show the diff result
x = diff(a, b) result: {'sat': {0: {'sat1': {0: {'xx': {0: {'hlp': {'rtrn': 'no'}}}}}}}} result i want display: "b2b": [ {"sat": [ { "somekey": "value", "sat1": [ { "hlp": { "return": "no", "xx": 0, "xx1": 0, "xx2": 0 }, } ] } ] } ] how can i display such result? i want to show the difference between the two dictionaries a and b? -
Which language better to use for server side scripting django or php or node.js what would be result if django vs php vs node.js
Please suggest me for strong webserver interpreter node.js,php,django -
django-cors-headers not working at all
Well, initially I had forgotten the middleware class but after adding it just worked fine ( It was a week ago ). Now, I am back to my workstation and I find it again not working. The ACCESS_CONTROL_ALLOW_ORIGIN headers are not at all being set. I have tried all that is, placing the middleware at top, before CommonMiddleware but it just doesn't work. This is my setting.py file : DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'account', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', ] # if DEBUG: # INSTALLED_APPS += 'corsheaders', # MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware', ] # else: # MIDDLEWARE = [] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = DEBUG This is the response I am getting : Date: Sun, 14 Jan 2018 09:35:09 GMT Server: WSGIServer/0.1 Python/2.7.14+ X-Frame-Options: SAMEORIGIN Content-Type: text/html; charset=utf-8 Content-Length: 146 -
Save Instance Nested Serializers in Django Rest Framework
I have problem with saving instance Live_In Nested Serializers in Django Rest Framework. Hope your guys help me! I think just a basic issue. My Serializers: I think it comes error when I write saving instance class UserEditSerializer(ModelSerializer): live_in = CityLiveInSerializer(many=False) about = serializers.CharField(source='profile.about') class Meta: model = User fields = [ 'username', 'live_in', 'about', ] def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.save() # Update Serializers Profile if (validated_data.get('profile') is not None): profile_data = validated_data.pop('profile') profile = instance.profile profile.about = profile_data.get('about', profile.about) profile.save() if (validated_data.get('live_in') is not None): live_in_data = validated_data.pop('live_in') ins = instance.city.live_in ins.live_in = live_in_data.get('name', ins.live_in) ins.save() return instance My City Model (Live_in) class City(BaseCity): class Meta(BaseCity.Meta): swappable = swapper.swappable_setting('cities', 'City') class BaseCity(Place, SlugModel): name = models.CharField(max_length=200, db_index=True, verbose_name="standard name") country = models.ForeignKey(swapper.get_model_name('cities', 'Country'), related_name='cities') Data sent by Postman (Json) { "live_in": { "name": "Encamp" } } TraceError: Exception Value: Cannot assign "u'Encamp'": "Profile.live_in" must be a "City" instance. File "/Users/lecongtoan/Desktop/FeedTrue/backend/api/authentication/views.py" in edit 43. serializer.save() File "/Users/lecongtoan/Desktop/FeedTrue/backend/api/authentication/serializers.py" in update 185. ins.live_in = live_in_data.get('name', ins.live_in) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py" in set 216. self.field.remote_field.model._meta.object_name, Exception Type: ValueError at /api/v1/users/account/edit/